-1

I don't understand why the code below subtracts an hour of a UNIX epoch timestamp (in timezone UTC+1):

import datetime
import pytz
start_dt = datetime.datetime.fromtimestamp( 1362268800 , pytz.utc )
print start_dt
# prints datetime.datetime(2013, 3, 3, 0, 0, tzinfo=<UTC>)
print int( start_dt.strftime("%s") )
# prints: 1362265200 (which is 2013-03-02T23:00Z ) <--- I expected 1362268800
print start_dt.strftime("%Y-%m-%dT%H:%M:%SZ")
# prints: 2013-03-03T00:00:00Z

I've since hacked around my problem by using calendar.timegm( start_ts.timetuple() ), but I fundamentally wonder what's wrong with the code above, and how to create datetime objects that are in UTC and where strftime would print the epoch timestamp.

Using "%s" is not specifically allowed according to the python docs. Should it be explicitly be not allowed (ie. raise an exception?) if it results in confusing results?

Using python 2.7.3

Emile Aben
  • 450
  • 3
  • 12
  • 1
    [various ways to convert date, datetime objects to POSIX timestamp](http://stackoverflow.com/a/8778548/4279) – jfs Mar 13 '13 at 09:26

1 Answers1

1

Using "%s" is not specifically allowed according to the python docs. Should it be explicitly be not allowed (ie. raise an exception?) if it results in confusing results?

From the docs:

The full set of format codes supported varies across platforms, because Python calls the platform C library’s strftime() function, and platform variations are common.

There is an open issue in the Python bug tracker "datetime.strftime('%s') should respect tzinfo" to add explicit support for "%s":

> it would appear the problem lies with strftime()

Yes, strftime('%s') ignores tzinfo at the moment. This is not a bug. Support for '%s' format code is incidental and not documented in Python.

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