Get an UTC timestamp with Python
Getting a localized timestamp is really simple with Python a simple
time.time()
does the tricks. But what about getting an UTC timestamp
regardless of the current system time?
To get this information many techniques exists, most common is to subtract the timestamp starts from the current time:
from datetime import datetime
int((datetime.utcnow() - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds())
This technique work greate but it requires setting by hand the timestamp start time. To avoid this the calendar module from the standard lib.can be used:
from calendar import timegm
from datetime import datetime
timegm(datetime.utcnow().utctimetuple())
As the two techniques returns the same results, let’s benchmark it:
In [1]: from datetime import datetime
In [2]: from calendar import timegm
In [3]: %timeit int((datetime.utcnow() - datetime(1970, 1, 1, 0, 0, 0, 0)).total_seconds())
The slowest run took 9.26 times longer than the fastest. This could mean that an intermediate result is being cached
100000 loops, best of 3: 1.83 µs per loop
In [4]: %timeit timegm(datetime.utcnow().utctimetuple())
The slowest run took 8.80 times longer than the fastest. This could mean that an intermediate result is being cached
100000 loops, best of 3: 3.31 µs per loop
We can see that the calendar technique is nearly two time longer than the subtract one but as the execution time is close to nothing (few micro-seconds) the choice stays open depending of your usage and maybe also the readability of your code.