est
est

Reputation: 11845

pytz alternative - using OS timezone as source?

Are there any simpler pytz alternative using OS timezone/dst as as source?

a ctypes wrapper or something doesn't require compiling would be welcome.

Edit: the beast

Upvotes: 2

Views: 2684

Answers (2)

jfs
jfs

Reputation: 414079

tzlocal module finds pytz timezone that corresponds to your OS local timezone on *nix and Win32:

from datetime import datetime
from tzlocal import get_localzone # $ pip install tzlocal

print(datetime.now(get_localzone()))
# -> 2015-01-27 07:20:52.163408+01:00

Your distribution may patch pytz module to use OS tz database instead of embed one (e.g., Ubuntu does it).

Upvotes: 2

James Henstridge
James Henstridge

Reputation: 43899

The C standard library functions expect to find the compiled time zone definition for local time at /etc/localtime. You can build a timezone object for it with pytz like so:

>>> import datetime
>>> import pytz
>>> localtime = pytz.build_tzinfo('localtime', open('/etc/localtime', 'rb'))
>>> print datetime.datetime.now(localtime)
2012-12-11 10:02:40.566735+08:00

One limitation here is that there is no way to determine what time zone /etc/localtime refers to from its content, so if you want to pickle date time objects or pass references to time zones between machines this could be problematic.

To allow time zone updates, some Linux distributions also write out the actual time zone name to /etc/timezone, so they can replace /etc/localtime with the correct compiled time zone definition. If your target OS does this, you could make use of the file like so:

>>> with open('/etc/timezone', 'r') as fp:
...     tzname = fp.read().strip()
... 
>>> localtime = pytz.timezone(tzname)
>>> print datetime.datetime.now(localtime)
2012-12-11 10:06:36.234822+08:00

Provided your target systems have this file, it is probably the better way to go.

Upvotes: 1

Related Questions