2

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

est
  • 11,429
  • 14
  • 70
  • 118
  • pytz is already a wrapper on the Olsen timezone database. Why would you not want to use that? – Keith Dec 11 '12 at 01:33
  • @Keith With pytz, you have to manually the specify the timezone (e.g. by reading `/etc/timezone`), which isn't the same on every OS. –  Dec 11 '12 at 01:35
  • There are POSIX functions for that, exposed in the `time` module. e.g. `time.timezone`. If your system is properly configured this should just work. – Keith Dec 11 '12 at 01:51
  • 1
    The `time` module won't give you an Olsen timezone, though, just a UTC offset, which isn't sufficient for pytz AFAIK. –  Dec 11 '12 at 04:54

2 Answers2

1

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.

James Henstridge
  • 42,244
  • 6
  • 132
  • 114
1

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).

jfs
  • 399,953
  • 195
  • 994
  • 1,670