Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django datetime field - convert to timezone in view

I have a Django model with a datetime field. When it is saved, the datetime field stored in my DB lose the timezone info, so it's saved as a naive datetime. In general this is not a problem since Django converts it back automatically when rendering the datetime field in the template.

But what about the view? Let's say I need the string representation of the datetime server-side. Depending on summer/winter time, my timezone could be GTM+1 or GMT+2, what makes the things more difficult.

So how do I apply the local tz conversion in the view? I have tried several ways with pytz. No success, ome entries are converted to GMT+1 and others to GMT+2 :(

Eg.

system_tz = pytz.timezone('Europe/Berlin')
local_dt = item.created_at.astimezone(system_tz)
local_dt = system_tz.normalize(local_dt)

Additional info:

  • Django 1.8.7.
  • settings.USE_TZ = True
  • MySQL
  • Why am I doing this? Because I have a table which loads all its rows on demand through AJAX. I need to prepare the datetime values with strftime() before send them to the client.
like image 682
pisapapiros Avatar asked Jan 28 '16 21:01

pisapapiros


2 Answers

start with this:

from django.utils import timezone

local_dt = timezone.localtime(item.created_at, pytz.timezone('Europe/Berlin'))

To convert to UTC+1:

from django.utils import timezone

local_dt = timezone.localtime(item.created_at, timezone.get_fixed_timezone(60))
  • How to get local time in current timezone (2nd question)
  • localtime()
  • get_fixed_timezone()
like image 60
vsd Avatar answered Oct 20 '22 01:10

vsd


There's no need to use django.utils to convert between timezones :

berlin = pytz.timezone('Europe/Berlin')
local_dt = item.created_at.astimezone(berlin)

Yet if you usually work with just one timezone it is convenient to store it in settings.TIME_ZONE = 'Europe/Berlin' and then

local_dt = timezone.localtime(item.created_at)

will convert it to your localtime.

like image 11
Antony Hatchkins Avatar answered Oct 20 '22 01:10

Antony Hatchkins