Convert datetime to Unix timestamp and convert it back in python

bridgewater picture bridgewater · Nov 6, 2013 · Viewed 437.8k times · Source

I have dt = datetime(2013,9,1,11), and I would like to get a Unix timestamp of this datetime object.

When I do (dt - datetime(1970,1,1)).total_seconds() I got the timestamp 1378033200.

When converting it back using datetime.fromtimestamp I got datetime.datetime(2013, 9, 1, 6, 0).

The hour doesn't match. What did I miss here?

Answer

DmitrySemenov picture DmitrySemenov · Jan 13, 2015

solution is

import time
import datetime
d = datetime.date(2015,1,5)

unixtime = time.mktime(d.timetuple())