how to get tz_info object corresponding to current timezone?
31,561
Solution 1
>>> import datetime
>>> today = datetime.datetime.now()
>>> insummer = datetime.datetime(2009,8,15,10,0,0)
>>> from pytz import reference
>>> localtime = reference.LocalTimezone()
>>> localtime.tzname(today)
'PST'
>>> localtime.tzname(insummer)
'PDT'
>>>
Solution 2
tzlocal
module that returns pytz
timezones works on *nix and win32:
from datetime import datetime
from tzlocal import get_localzone # $ pip install tzlocal
# get local timezone
local_tz = get_localzone()
print local_tz.localize(datetime(2012, 1, 15))
# -> 2012-01-15 00:00:00+04:00 # current utc offset
print local_tz.localize(datetime(2000, 1, 15))
# -> 2000-01-15 00:00:00+03:00 # past utc offset (note: +03 instead of +04)
print local_tz.localize(datetime(2000, 6, 15))
# -> 2000-06-15 00:00:00+04:00 # changes to utc offset due to DST
Note: it takes into account both DST and non-DST utc offset changes.
Solution 3
Python 3.7:
import datetime
datetime.datetime.now().astimezone().tzinfo
Solution 4
time.timezone
returns current timezone offset. there is also a datetime.tzinfo
, if you need more complicated structure.
Solution 5
This following code snippet returns time in a different timezone irrespective of the timezone configured on the server.
# pip install pytz tzlocal
from tzlocal import get_localzone
from datetime import datetime
from pytz import timezone
local_tz = get_localzone()
local_datetime = datetime.now(local_tz)
zurich_tz = timezone('Europe/Zurich')
zurich_datetime = zurich_tz.normalize(local_datetime.astimezone(zurich_tz))
Author by
random guy
Updated on August 09, 2020Comments
-
random guy almost 4 years
Is there a cross-platform function in
python
(orpytz
) that returns atzinfo
object corresponding to the timezone currently set on the computer?environment variables cannot be counted on as they are not cross-platform