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?
I think I figured it out: computes number of seconds since epoch, then converts to a local timzeone using time.localtime, and then converts the time struct back into a datetime...
It applies the summer/winter DST correctly:
A simple (but maybe flawed) way that works in Python 2 and 3:
Its advantage is that it's trivial to write an inverse function
Here is another way to change timezone in datetime format (I know I wasted my energy on this but I didn't see this page so I don't know how) without min. and sec. cause I don't need it for my project:
You can't do it with only the standard library as the standard library doesn't have any timezones. You need pytz or dateutil.
Or well, you can do it without pytz or dateutil by implementing your own timezones. But that would be silly.
Building on Alexei's comment. This should work for DST too.
You can't do it with standard library. Using pytz module you can convert any naive/aware datetime object to any other time zone. Lets see some examples using Python 3.
To convert a naive object to any other time zone, first you have to convert it into aware datetime object. You can use the
replace
method for converting a naive datetime object to an aware datetime object. Then to convert an aware datetime object to any other timezone you can useastimezone
method.The variable
pytz.all_timezones
gives you the list of all available time zones in pytz module.Because
now
method returns current date and time, so you have to make the datetime object timezone aware first. Thelocalize
function converts a naive datetime object into a timezone-aware datetime object. Then you can use theastimezone
method to convert it into another timezone.