Python provides different packages (datetime
, time
, calendar
) as can be seen here in order to deal with time. I made a big mistake by
At least in python3, this works:
>>> datetime.strftime(datetime.utcnow(), "%s")
'1587503279'
Python 3 seconds with microsecond decimal resolution:
from datetime import datetime
print(datetime.now().timestamp())
Python 3 integer seconds:
print(int(datetime.now().timestamp()))
datetime.utcnow().timestamp()
!datetime.utcnow()
is a non-timezone aware object. See reference: https://docs.python.org/3/library/datetime.html#aware-and-naive-objects
For something like 1am UTC:
from datetime import timezone
print(datetime(1970,1,1,1,0,tzinfo=timezone.utc).timestamp())
or
print(datetime.fromisoformat('1970-01-01T01:00:00+00:00').timestamp())
if you remove the tzinfo=timezone.utc
or +00:00
, you'll get results dependent on your current local time. Ex: 1am on Jan 1st 1970 in your current timezone - which could be legitimate - for example, if you want the timestamp of the instant when you were born, you should use the timezone you were born in. However, the timestamp from datetime.utcnow().timestamp()
is neither the current instant in local time nor UTC. For example, I'm in GMT-7:00 right now, and datetime.utcnow().timestamp()
gives a timestamp from 7 hours in the future!
I like this method:
import datetime, time
dts = datetime.datetime.utcnow()
epochtime = round(time.mktime(dts.timetuple()) + dts.microsecond/1e6)
The other methods posted here are either not guaranteed to give you UTC on all platforms or only report whole seconds. If you want full resolution, this works, to the micro-second.
I would use time.time() to get a timestamp in seconds since the epoch.
import time
time.time()
Output:
1369550494.884832
For the standard CPython implementation on most platforms this will return a UTC value.