Python provides different packages (datetime
, time
, calendar
) as can be seen here in order to deal with time. I made a big mistake by
from datetime import datetime as dt
dt.utcnow().strftime("%s")
Output:
1544524990
Does this help?
from datetime import datetime
import calendar
d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
print unixtime
How to convert Python UTC datetime object to UNIX timestamp
python2 and python3
it is good to use time module
import time
int(time.time())
1573708436
you can also use datetime module, but when you use strftime('%s'), but strftime convert time to your local time!
python2
from datetime import datetime
datetime.utcnow().strftime('%s')
python3
from datetime import datetime
datetime.utcnow().timestamp()
Or just simply using the datetime standard module
In [2]: from datetime import timezone, datetime
...: int(datetime.now(tz=timezone.utc).timestamp() * 1000)
...:
Out[2]: 1514901741720
You can truncate or multiply depending on the resolution you want. This example is outputting millis.
If you want a proper Unix timestamp (in seconds) remove the * 1000
#First Example:
from datetime import datetime, timezone
timstamp1 =int(datetime.now(tz=timezone.utc).timestamp() * 1000)
print(timstamp1)
Output: 1572878043380
#second example:
import time
timstamp2 =int(time.time())
print(timstamp2)
Output: 1572878043
import time
int(time.time())
Output:
1521462189