Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve timezone aware DateTimeField in Django

Tags:

django

pytz

In my models, I have a DateTimeField say

class ReturnEvent(models.Model):
  book_title = models.CharField()
  return_time = models.DateTimeField()

When I retrieve the return_time to be printed, for example:

return_event = ReturnEvent.objects.get(id=1)
print(return_event.return_time.strftime("%H:%M"))

I am seeing the datetime unaware time like:

2016-06-18 08:18:00+00:00

However, I like to see the local time using strftime.

2016-06-18 10:18:00+02:00

Is there a quick solution for this?

like image 838
bryan.blackbee Avatar asked May 30 '16 13:05

bryan.blackbee


1 Answers

If you have USE_TZ = True in your settings, Django stores all the datetime objects in the database as UTC and convert them to your TIME_ZONE=XYZ from settings.py on the fly when rendering in the templates.

That is why, when retrieved from the database, datetime object is timezone aware but it has UTC as its timezone (hence +00:00 in 2016-06-18 08:18:00+00:00). As, you are converting the time to str yourself (and not rendering in the template) so Django does not convert it to your TIME_ZONE setting. You need to convert it yourself to your desired TimeZone.

If you want to convert it to the TimeZone from your TIME_ZONE setting, you can do

from django.utils import timezone
to_tz = timezone.get_default_timezone()
print return_event.return_time.astimezone(to_tz).strftime("%H:%M")
like image 122
Muhammad Tahir Avatar answered Sep 29 '22 09:09

Muhammad Tahir