On Sun, Jun 9, 2013 at 5:07 AM, XQ Kuang <xuqingku...@gmail.com> wrote: > Hi. > > The form of my app posted the expired_time with int timestamp just like > 1371409201 and then converted it to datetime object. > >> expire_datetime = >> datetime.fromtimestamp(profile_form.cleaned_data['expired_time']) >> >> request.session.set_expiry(expire_datetime) > > > But the code raised 500 error. > >> Traceback (most recent call last): >> File >> "/usr/local/python/site-packages/django-1.5/django/core/handlers/base.py", >> line 187, in get_response response = middleware_method(request, response) >> File >> "/usr/local/python/site-packages/django-1.5/django/contrib/sessions/middleware.py", >> line 32, in process_response max_age = request.session.get_expiry_age() >> File >> "/usr/local/python/site-packages/django-1.5/django/contrib/sessions/backends/base.py", >> line 195, in get_expiry_age delta = expiry - modification TypeError: can't >> subtract offset-naive and offset-aware datetimes > > > I see the doc[1] datetime is acceptable for the function, but it doesn't. > > Is it a bug ? > > Thx a lot. > > [1] > https://docs.djangoproject.com/en/dev/topics/http/sessions/#django.contrib.sessions.backends.base.SessionBase.set_expiry >
Yes, it is a bug - in your code! You cannot mix naive and non naive datetimes together - naive datetimes are datetimes without a timezone. If you have USE_TZ=True in your settings.py, then django will be using non naive datetimes throughout, and so you must do also. Django provides a lot of utils to allow you to make a naive datetime into a non naive: https://docs.djangoproject.com/en/1.5/ref/utils/#django-utils-timezone So code like this would work: from django.utils.timezone import make_aware, get_current_timezone expire_datetime = datetime.fromtimestamp(profile_form.cleaned_data['expired_time']) expire_datetime = make_aware(expire_datetime, get_current_timezone()) request.session.set_expiry(expire_datetime) Cheers Tom -- You received this message because you are subscribed to the Google Groups "Django users" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscr...@googlegroups.com. To post to this group, send email to django-users@googlegroups.com. Visit this group at http://groups.google.com/group/django-users?hl=en. For more options, visit https://groups.google.com/groups/opt_out.