Python get system timezone

Get system local timezone in python

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 )

5 Answers 5

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()) 
from tzlocal import get_localzone local_tz = get_localzone() 

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.

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.

Correct, this gives the non-DST local timezone. If you need to know if DST is active you can use time.localtime( ).tm_isdst > 0

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)

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

Читайте также:  empty demo

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) 

Источник

Get time zone information of the system in Python?

I want to get the default timezone (PST) of my system from Python. What’s the best way to do that? I’d like to avoid forking another process.

9 Answers 9

time.tzname returns 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.

Читайте также:  Сколько процентов составляет число от числа php

To take this one further, you can use time.tzname[time.daylight] to get the name of the current timezone, accounting for daylight saving time.

Again, ‘time.daylight’ does not indicate that DST is active. It merely indicates whether or not DST is observed by the timezone. You’re looking for ‘time.localtime().tm_isdst’.

Just to add for Windows users, the values for timezone was defined in `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones`

time.tzname may return a wrong value if the local timezone had different abbreviations in the past (Python uses values from January, July or the current (import/ tzset() time) value). tzlocal module could be used to get the correct tzname for a given date.

Gives a UTC offset like in ThomasH’s answer, but takes daylight savings into account.

>>> import time >>> offset = time.timezone if (time.localtime().tm_isdst == 0) else time.altzone >>> offset / 60 / 60 * -1 -9 

The value of time.timezone or time.altzone is in seconds West of UTC (with areas East of UTC getting a negative value). This is the opposite to how we’d actually like it, hence the * -1.

time.localtime().tm_isdst will be zero if daylight savings is currently not in effect (although this may not be correct if an area has recently changed their daylight savings law).

EDIT: marr75 is correct, I’ve edited the answer accordingly.

Источник

how to get tz_info object corresponding to current timezone?

Is there a cross-platform function in python (or pytz ) that returns a tzinfo object corresponding to the timezone currently set on the computer? environment variables cannot be counted on as they are not cross-platform

8 Answers 8

>>> 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' >>> 

That warning applies to reference.USTimeZone , which uses the pre-2007 rules for US DST. However reference.LocalTimezone , used here, probes the behavior of time.localtime , whose correctness is maintained with the system libraries. reference.LocalTimezone gives the correct DST transitions both before and after the 2007 change in US rules; I haven’t tested for other countries.

Читайте также:  Css количество дочерних элементов

@rob: wrong. Do not use LocalTimezone() . pytz provides historical timezone data while time.timezone , time.altzone (used by LocalTimezone() ) are constants i.e., at best they reflect the most recent timezone definition. The local timezone may have different utc offsets in the past/future e.g., try Europe/Moscow timezone in 2010-2015 and see what happens for yourself.

@J.F.Sebastian From my understanding, that will only affect handling historic times or arithmetic. For my purposes I only need to know the local system offset from UTC to parse future timestamps from the system (e.g. syslogs), then convert to UTC right away. Would it be safe to use LocalTimezone() for that?

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.

Источник

Оцените статью