Question

I'm creating a simple Django API where access tokens are used. The idea is that, when a user requests a token, said token is valid for the next 7 hours.

However when generating the token I obtain a Python NonExistentTimeError. Code is:

 #Django view
 ...
 expires = datetime.datetime.now() + datetime.timedelta(hours=7)

 token = APIMasterToken.objects.create(
     token=token,
     expiration_date=expires
 )

However I obtain an exception generating a token with said date:

NonExistentTimeError at /api/obtain_master_token/
2013-03-10 02:05:12.179508

What does this error mean and how can I solve it?

EDIT: I just read the documentation and it would appear this error is raised when a day occurs that has a clock change following DST. However, I don't know how to solve the problem. Shouldn't the timedelta function take care of this?

Was it helpful?

Solution

Django expects to work with timezone aware datetime objects.

From the Django documentation, the now() call would become:

import datetime
from django.utils.timezone import utc

now = datetime.datetime.utcnow().replace(tzinfo=utc)
expires = now + datetime.timedelta(hours=7)

Better still, use the now() function from django.utils.timezone.

Both datetime.now() and datetime.utcnow() return naive datetime objects which is not what Django requires. With a time zone applied to expires, Django is then able to convert back to UTC for storage as UTC in the database backend.

The NonExistentTimeError is actually thrown by code from the pytz module. The pytz documentation is definitely worth reading as there's many gotchas when dealing with time zones.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top