How to use datetime.tzinfo in Python?

10.3k views Asked by At

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?

2

There are 2 answers

0
dacada On

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.

1
stjernaluiht On

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.