Python datetime.timestamp() issue -


i find datetime.timestamp() function return different value on linux , windows. here simple to replicate it:

from datetime import date, time, datetime, timedelta  def main():      dt = datetime(2000, 1, 1)     edt = datetime(2006, 12, 31)      fname = 't1.csv'     f = open(fname, 'w')     f.write('date,timestamp\n')     while dt <= edt:         f.write('{0:%y-%m-%d},{1:.0f}\n'.format(dt, dt.timestamp()))         dt += timedelta(days=1)     f.close()  return 0 

here last different part windows: (windows7 64 + python3.4.3 64)

... 2006-10-30,1162180800 2006-10-31,1162267200 2006-11-01,1162353600 2006-11-02,1162440000 2006-11-03,1162526400 2006-11-04,1162612800 2006-11-05,1162699200 ... 

here corresponding linux output: (redhat6 64 + python 3.4.3 64)

... 2006-10-30,1162184400 2006-10-31,1162270800 2006-11-01,1162357200 2006-11-02,1162443600 2006-11-03,1162530000 2006-11-04,1162616400 2006-11-05,1162702800 ... 

systems using est automatic dst adjustment. observations:

  • the linux output seems correct
  • no difference observed after 2006 (i did not test above 12/31/2015)
  • the difference seems 1 hour/3600 seconds
  • the difference seems happen in days around dst change in year (or around time eu/us has different dst change date.)

just wondering why timestamp() function behaves differently on windows , linux.

datetime.timestamp() on naive datetime object calls mktime() internally i.e., input interpreted local time. local time definitions may differ between systems.

c mktime() may return wrong result if local timezone had different utc offset in past , historical timezone database not used. python has no access the tz database on windows.

you may different results if applications use different tzdata versions. may different results ambiguous times (e.g., during dst transitions) if different mktime() implementations used (all else being equal).

to same result on different systems, use pytz module (the same version on different systems uses bundled python package zoneinfo):

#!/usr/bin/env python3 datetime import datetime import pytz  # $ pip install pytz  tz = pytz.timezone('america/new_york') tt in [(2006, 10, 30),            (2006, 10, 31),            (2006, 11, 1),            (2006, 11, 2),            (2006, 11, 3),            (2006, 11, 4),            (2006, 11, 5)]:     dt = datetime(*tt)     ts = tz.localize(dt, is_dst=none).timestamp()     print("{dt:%y-%m-%d},{ts:.0f}".format(**vars())) 

output (pytz.__version__ == 2014.10)

2006-10-30,1162184400 2006-10-31,1162270800 2006-11-01,1162357200 2006-11-02,1162443600 2006-11-03,1162530000 2006-11-04,1162616400 2006-11-05,1162702800 

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -