Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 )

like image 761
ntg Avatar asked Jan 28 '16 09:01

ntg


People also ask

How do I get system time in Python?

Datetime module comes built into Python, so there is no need to install it externally. To get both current date and time datetime. now() function of DateTime module is used. This function returns the current local date and time.

Which Python library is used for timezone?

pytz brings the Olson tz database into Python. This library allows accurate and cross platform timezone calculations using Python 2.4 or higher. It also solves the issue of ambiguous times at the end of daylight saving time, which you can read more about in the Python Library Reference ( datetime. tzinfo ).


2 Answers

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()
like image 66
Selcuk Avatar answered Oct 06 '22 23:10

Selcuk


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.

like image 22
Martin Evans Avatar answered Oct 06 '22 22:10

Martin Evans