Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django timezone: feeling a bit confused

So, we have 'Europe/Moscow' TZ in our settings. Currently this means daylight saving (this is going to change in the future, but at the moment it's UTC+03/04).

I understand that this TZ is used when saving dates to the DB, and when extracting them.

Now, I have to serialize the datetime object to ISO string, including the UTC offset. What is the correct way of doing this?

The dates don't contain the TZ info (i.e. d.strftime('%z') is empty)

I think I could convert them to UTC and serialize with +00:00, but how do I convert them to UTC if I don't know if the specific date is +03 (Moscow winter) or +04 (Moscow summer)

like image 310
Guard Avatar asked Jan 20 '23 03:01

Guard


1 Answers

how do I convert them to UTC if I don't know if the specific date is +03 (Moscow winter) or +04 (Moscow summer)

There is no need for UTC conversion, pytz handles such thing for you.

Here's the code to convert from timezone-naive datetime to ISO with timezone offset:

from datetime import datetime
from pytz import timezone

server_timezone = timezone('Europe/Moscow')

server_timezone.localize(datetime(2011, 1, 1)).isoformat()
>>> '2011-01-01T00:00:00+03:00'

server_timezone.localize(datetime(2011, 7, 1)).isoformat()
>>> '2011-07-01T00:00:00+04:00'
like image 187
sayap Avatar answered Jan 26 '23 00:01

sayap