mrtasktat
mrtasktat

Reputation: 345

Python: UTC timestamp from pytz localized timestamp

I am trying to convert timestamp strings to the equivalent seconds from the unix epoch using pytz. I'm puzzled by the output of the below code.

import datetime
import pytz

exif = '2008:05:03 16:23:16'
dtexif = datetime.datetime.strptime(exif, '%Y:%m:%d %H:%M:%S')
print dtexif

zrh = pytz.timezone('Europe/Zurich')
tztime = zrh.localize(dtexif)
print tztime

tzfloat = float(tztime.astimezone(pytz.utc).strftime('%s'))
utctime = pytz.utc.localize(datetime.datetime.fromtimestamp(tzfloat))
print utctime

print 'seconds since epoch: %.1f' % tzfloat

With pytz-2016.10, it prints:

2008-05-03 16:23:16
2008-05-03 16:23:16+02:00
2008-05-03 15:23:16+00:00
seconds since epoch: 1209849796.0

I would expect the second last line to be:

2008-05-03 14:23:16+00:00

And I'm baffled by the last line, which represents 2008-05-03T21:23:16+00:00 according to http://www.unixtimestamp.com/

Where am I going wrong?

Upvotes: 0

Views: 4132

Answers (1)

mrtasktat
mrtasktat

Reputation: 345

Looks like I didn't search hard enough, this was addressed here: python - datetime with timezone to epoch

The line to calculate tzfloat should be:

tzfloat = (tztime - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()

I had wrongly assumed the timestamp would already be relative to the epoch.

Upvotes: 3

Related Questions