12/09/2015

Covert datetime to unixtime and back

Very often I need to convert datetime into unix timestamp to pass datetime values into javascript json response. One way to do this using standard library is:

import time
import datetime
d = datetime.date(2015,11,9)

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

# add timezone if needed
unixtime += time.timezone
reverse conversion is much easier:

import datetime
dt = datetime.datetime.fromtimestamp(1447016400.0)

No comments:

Post a Comment