简体   繁体   中英

One hour added when converting date to unix timestamp

When converting a date to unix timestamp and formatting it, one hour is being added. What I am doing wrong?

>>> import dateutil.parser
>>> import datetime

>>> date_str = "2014-12-09T19:00:00+1100"
>>> date = dateutil.parser.parse(date_str)
>>> unix = int(date.strftime('%s'))

>>> date_str
'2014-12-09T19:00:00+1100'

>>> date
2014-12-09 19:00:00+11:00

>>> print(unix)
1418115600

>>> datetime.datetime.fromtimestamp( unix).strftime('%Y-%m-%d %H:%M:%S')
2014-12-09 20:00:00

The hour has been changed from 19:00 to 20:00. I am suspecting this has something to do with time zone. But I have no clue what exactly is going wrong.

I used Epoch calculator to verify the unix timestamp. It seems that the one hour is being added in the process of convert date variable to unix timestamp. (date = dateutil.parser.parse(date_str))

Any help appreciated!

You can obtain a Unix timestamp from a datetime object by doing:

import pytz

timestamp = int((datetime_obj - datetime.datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds())

This requires the pytz library. We're using total_seconds() so this solution is Python 2.7+.

In your case that gives you the timestamp 1418112000 which matches the original datetime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM