Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use datetime.tzinfo in Python?

Tags:

I have no idea how to use datetime.tzinfo module. I have to convert a datetime data from UTC to local timezone and if I retrieve '+2'(which means gmt+2) how do I convert this to tzinfo object?

Also, is it possible to convert from UTC to local timezone with daylight saving time applied automatically? How do I set to subtract one hour automatically only during dst?

like image 449
Charlie Lee Avatar asked Sep 05 '17 10:09

Charlie Lee


2 Answers

Python doesn't really implement well timezones. According to the documentation, tzinfo is just an abstract class meant to be implemented by the user.

I'd recommend the third party pytz module for dealing with timezones.

like image 93
dacada Avatar answered Sep 30 '22 15:09

dacada


You can use tzoffset to set the timezone offset that you retrieve. For example, if you get "+2", parse that string so that n = 2:

from dateutil.tz import tzoffset

utc_dt = your_datetime.replace(tzinfo=tzoffset("UTC+0",0))
local_dt = utc_dt.astimezone(tzoffset("UTC+{}".format(n), n*60*60))

The variable utc_dt was used just to be sure that your original datetime has a the right UTC timezone as attribute, otherwise it won't work. Then you can set the offset in seconds for your target local time.

I'm not sure if it's possible to apply DST just knowing the UTC/GMT offset, because some countries in a timezone may not apply it. If you had the exact localization, like "Europe/Vienna", you could use the pytz library and the datetime.dst() method to determine whether to subtract one hour or not.

like image 27
stjernaluiht Avatar answered Sep 30 '22 13:09

stjernaluiht