Get system local timezone in python
Asked Answered
C

5

22

Seems strange, but I cannot find an easy way to find the local timezone using pandas/pytz in Python.

I can do:

>>> pd.Timestamp('now', tz='utc').isoformat()
Out[47]: '2016-01-28T09:36:35.604000+00:00'
>>> pd.Timestamp('now').isoformat()
Out[48]: '2016-01-28T10:36:41.830000'
>>> pd.Timestamp('now').tz_localize('utc') - pd.Timestamp('now', tz='utc')
Out[49]: Timedelta('0 days 01:00:00')

Which will give me the timezone, but this is probably not the best way to do it... Is there a command in pytz or pandas to get the system time zone? (preferably in python 2.7 )

Cerebrovascular answered 28/1, 2016 at 9:48 Comment(2)
related, if not dupe: Python: Figure out local timezoneAeriel
The fuxking python have no built-in way to do this.Procurable
S
29

I don't think this is possible using pytz or pandas, but you can always install python-dateutil or tzlocal:

from dateutil.tz import tzlocal
datetime.now(tzlocal())

or

from tzlocal import get_localzone
local_tz = get_localzone()
Sandpiper answered 28/1, 2016 at 10:4 Comment(1)
If you want the actual timezone name, as a string, you can use datetime.now(tzlocal()).tzname(). It will output a three letter time zone code. For example, MST for Mountain Time.Fluorene
J
22

time.timezone should work.

The offset of the local (non-DST) timezone, in seconds west of UTC (negative in most of Western Europe, positive in the US, zero in the UK).

Dividing by 3600 will give you the offset in hours:

import time

print(time.timezone / 3600.0)

This does not require any additional Python libraries.

Jordon answered 28/1, 2016 at 10:11 Comment(2)
This doesn't take into account Daylight savings.Plains
Correct, this gives the non-DST local timezone. If you need to know if DST is active you can use time.localtime( ).tm_isdst > 0Jordon
F
18

I have found that in many cases this works: (Since Python 3.6)

from datetime import datetime

# use this extension and it adds the timezone
tznow = datetime.now().astimezone()
print(tznow.isoformat())
2020-11-05T06:56:38.514560-08:00

# It shows that it does have a valid timezone
type(tznow.tzinfo)
<class 'datetime.timezone'>

I find this handy as it does not depend on external packages. It appears to work only in Python3 (but not in Python2)

Fraternity answered 5/11, 2020 at 15:15 Comment(0)
M
3

Quite a few locale time related settings from OS level is covered by time module

import time

# Since Python 3.3
local_time = time.localtime()         # returns a `time.struct_time`
tzname_local = local_time.tm_zone     # 'EST'
dst = local_time.tm_isdst             # _from docs_: may be set to 1 when daylight savings time is in effect, 
                                      # and 0 when it is not. A value of -1 indicates that this is not known, 
                                      # and will usually result in the correct state being filled in.

tm_gmtoff and tm_zone attributes are available on platforms with C library supporting the corresponding fields in struct tm.
see: https://docs.python.org/3/library/time.html#time.struct_time

# At least from Python 2.7.18
local_tzname = time.tzname            # 'EST'

A tuple of two strings: the first is the name of the local non-DST timezone, the second is the name of the local DST timezone. If no DST timezone is defined, the second string should not be used. see: https://docs.python.org/2.7/library/time.html#time.tzname)

Another trick is to use datetime.now().astimezone() as found here and the reason why it fails on python 2.x

from datetime import datetime

# Python 3 will return a datetime with local timezone,
local_now = datetime.now().astimezone()    

# Doesn't work on python 2.x 
# datetime.now().astimezone()                -> TypeError: Required argument 'tz' (pos 1) not found
# datetime.now().astimezone(dateutil.tz.UTC) -> ValueError: astimezone() cannot be applied to a naive datetime

local_tz = local_now.tzinfo  # datetime.timezone
local_tzname = local_tz.tzname(local_now)
print(local_tzname) 
Mizell answered 20/3, 2021 at 16:55 Comment(1)
Note that the time.localtime().tm_zone returns an abbreviation which is often not reusable if you pass it to many libraries (typically anything that uses pytz as a backend), as some abbreviations are not unique. The datetime approach returns an object with the timedelta from UTC in seconds, which is more reliable.Charette
B
1

While it doesn't use pytz/Pandas, the other answers don't either, so I figured I should post what I'm using on mac/linux:

import subprocess
timezone = subprocess.check_output("date +%Z")

Benefits over the other answers: respects daylight savings time, doesn't require additional libraries to be installed.

Ballou answered 2/11, 2018 at 19:2 Comment(3)
Parsing the output of an external command is brittle unless the output format is specified, and could break if the output format changes. It would be better to use the output of date +%Z without parsing.Contessacontest
spawning a new process costs more resources to the system. This answer, while valid, should be the last choice within I/O intensive systems. This is relative, of course: For example, making this subprocess call inside a server-side HTTP handler could make your application more sensitive to DDoS. If you put this inside a lambda it would also make the call longer and literally more expensive. But, if you just want to write a quick script that does not to be portable with windows, this answer should be a quicker way of getting it done.Herculean
Not sure if YMMV based on other versions of Python, but I'm using 3.7.3, and this is the syntax required: timezone = subprocess.check_output(["date", "+%Z"]); I guess by default a shell isn't used, so including arguments in a single string just gets the function to look for a like-named file which fails.Scoff

© 2022 - 2025 — McMap. All rights reserved.