I have a python datetime instance that was created using datetime.utcnow() and persisted in database.
For display, I would like to convert the datetime instance retrieved from the database to local datetime using the default local timezone (i.e., as if the datetime was created using datetime.now()).
How can I convert the UTC datetime to a local datetime using only python standard library (e.g., no pytz dependency)?
It seems one solution would be to use datetime.astimezone( tz ), but how would you get the default local timezone?
In Python 3.3+:
In Python 2/3:
Using
pytz
(both Python 2/3):Example
Output
Python 3.3 Python 2 pytzNote: it takes into account DST and the recent change of utc offset for MSK timezone.
I don't know whether non-pytz solutions work on Windows.
The easiest way I have found is to get the time offset of where you are, then subtract that from the hour.
This works for me, in Python 3.5.2.
The standard Python library does not come with any
tzinfo
implementations at all. I've always considered this a surprising shortcoming of the datetime module.The documentation for the tzinfo class does come with some useful examples. Look for the large code block at the end of the section.