Wednesday, February 13, 2013

Python seconds since epoch timestamp

Getting a 'seconds since epoch' timestamp in python is easy, but there are also some wrong ways to do it, a number of which are being recommended on Stack Overflow. time.time() seems to be the best choice:
# System time since epoch for reference (--utc actually makes no difference)
In [30]: !date --utc +%s
1360802215

# Correct!
In [31]: time.time()
Out[31]: 1360802218.887309

# This one is wrong, it mixes local and UTC
In [32]: time.mktime(time.gmtime())
Out[32]: 1360831021.0

# This is also correct, but requires a whole other module
In [33]: calendar.timegm(time.gmtime())
Out[33]: 1360802225

No comments: