Python: Figure out local timezone Python: Figure out local timezone python python

Python: Figure out local timezone


In Python 3.x, local timezone can be figured out like this:

import datetimeLOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone.utc).astimezone().tzinfo

It's a tricky use of datetime's code .

For python < 3.6, you'll need

import datetimeLOCAL_TIMEZONE = datetime.datetime.now(datetime.timezone(datetime.timedelta(0))).astimezone().tzinfo


Try dateutil, which has a tzlocal type that does what you need.


to compare UTC timestamps from a log file with local timestamps.

It is hard to find out Olson TZ name for a local timezone in a portable manner. Fortunately, you don't need it to perform the comparison.

tzlocal module returns a pytz timezone corresponding to the local timezone:

from datetime import datetimeimport pytz # $ pip install pytzfrom tzlocal import get_localzone # $ pip install tzlocaltz = get_localzone()local_dt = tz.localize(datetime(2010, 4, 27, 12, 0, 0, 0), is_dst=None)utc_dt = local_dt.astimezone(pytz.utc) #NOTE: utc.normalize() is unnecessary here

Unlike other solutions presented so far the above code avoids the following issues:

  • local time can be ambiguous i.e., a precise comparison might be impossible for some local times
  • utc offset can be different for the same local timezone name for dates in the past. Some libraries that support timezone-aware datetime objects (e.g., dateutil) fail to take that into account

Note: to get timezone-aware datetime object from a naive datetime object, you should use*:

local_dt = tz.localize(datetime(2010, 4, 27, 12, 0, 0, 0), is_dst=None)

instead of:

#XXX fails for some timezoneslocal_dt = datetime(2010, 4, 27, 12, 0, 0, 0, tzinfo=tz)

*is_dst=None forces an exception if given local time is ambiguous or non-existent.

If you are certain that all local timestamps use the same (current) utc offset for the local timezone then you could perform the comparison using only stdlib:

# convert a naive datetime object that represents time in local timezone to epoch timetimestamp1 = (datetime(2010, 4, 27, 12, 0, 0, 0) - datetime.fromtimestamp(0)).total_seconds()# convert a naive datetime object that represents time in UTC to epoch timetimestamp2 = (datetime(2010, 4, 27, 9, 0) - datetime.utcfromtimestamp(0)).total_seconds()

timestamp1 and timestamp2 can be compared directly.

Note:

  • timestamp1 formula works only if the UTC offset at epoch (datetime.fromtimestamp(0)) is the same as now
  • fromtimestamp() creates a naive datetime object in the current local timezone
  • utcfromtimestamp() creates a naive datetime object in UTC.