0

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?

2
  • Daylight saving time? Commented Jan 30, 2017 at 5:57
  • It looks like pytz already took care of that via localize(). The right offset (+2:00) for daylight savings is applied. Commented Jan 30, 2017 at 6:05

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.