Django datetime field - timezone conversion

I have a Django model with a datetime field. When it is saved, the datetime field stored in my DB loses timezone information, so it is saved as a datetime naive . In general, this is not a problem, since Django will automatically convert it back when rendering the datetime field in the template.

But what about submission? Let's say I need a string representation of the server side of datetime. Depending on the summer / winter time, my time zone may be GTM + 1 or GMT + 2, which complicates the situation.

So, how do I apply the local tz transformation in the view ? I tried several ways with pytz. There is 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 Information:

  • Django 1.8.7.
  • settings.USE_TZ = True
  • MySQL
  • Why am I doing this? Because I have a table that loads all its rows on demand via AJAX. I need to prepare datetime values ​​using strftime () before sending them to the client.
+5
source share
2 answers
 from django.utils import timezone local_dt = timezone.localtime(item.created_at, pytz.timezone('Europe/Berlin')) 

To match UTC + 1:

 from django.utils import timezone local_dt = timezone.localtime(item.created_at, timezone.get_fixed_timezone(60) 
+4
source

There is no need to use django.utils to convert between time zones:

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

However, if you usually work with only one time zone, it is convenient to store it in settings.TIME_ZONE = 'Europe/Berlin' , and then

 local_dt = timezone.localtime(item.created_at) 

converts it to local time.

0
source

Source: https://habr.com/ru/post/1241758/


All Articles