bryan.blackbee
bryan.blackbee

Reputation: 1954

Retrieve timezone aware DateTimeField in Django

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?

Upvotes: 9

Views: 6663

Answers (1)

Muhammad Tahir
Muhammad Tahir

Reputation: 5184

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")

Upvotes: 25

Related Questions