1

Why does the following happen?

from datetime import datetime
import pytz

d = pytz.utc.localize(datetime.utcnow())
print float(d.strftime('%s')) - float(d.replace(tzinfo=None).strftime('%s')) # 3600.0

Why is it off by one hour whether or not tzinfo is included? I'm assuming it has to do with DST, but... UTC does not have DST.

d.timetuple()
# time.struct_time(tm_year=2013, tm_mon=10, tm_mday=21, tm_hour=17, tm_min=44, tm_sec=40, tm_wday=0, tm_yday=294, tm_isdst=0)
d.replace(tzinfo=None).timetuple()
# time.struct_time(tm_year=2013, tm_mon=10, tm_mday=21, tm_hour=17, tm_min=44, tm_sec=40, tm_wday=0, tm_yday=294, tm_isdst=-1)

So, the difference is tm_isdst is 0 or -1. Both seem very "No DST-ish".

Just not thrilled with the workaround.

Update:

After reading some docs (http://docs.python.org/2/library/time.html#time.mktime) It appears mktime() outputs "localtime" not UTC as I had thought. Which confuses everything.

dlamotte
  • 6,145
  • 4
  • 31
  • 40
  • 1
    your title mentions *"epoch time"*. This answer shows [how to convert datetime.date and datatime.datetime to POSIX timestamp](http://stackoverflow.com/a/8778548/4279) – jfs Mar 27 '14 at 08:26

1 Answers1

0

.strftime('%s') is not supported by Python. Do not use it.

On systems where it works, it interprets the datetime object as time in local timezone i.e., datetime.now().strftime('%s') might return value near time.time().

To find out utc offset or whether DST is in effect for a given local time, you could call d.utcoffset(), d.dst() where d is a datetime object with pytz timezone.

>>> import pytz
>>> d = datetime.now(pytz.utc)
>>> d.utcoffset()
datetime.timedelta(0)
>>> d.dst()
datetime.timedelta(0)

As expected UTC offset is zero for UTC timezone and there is no DST transitions so .dst() is always zero all year round.

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