How to get the seconds since epoch from the time + date output of gmtime()?


How do you do reverse gmtime(), where you put the time + date and get the number of seconds?

I have strings like 'Jul 9, 2009 @ 20:02:58 UTC', and I want to get back the number of seconds between the epoch and July 9, 2009.

I have tried time.strftime but I don't know how to use it properly, or if it is the correct command to use.

1/14/2018 3:41:42 AM

Accepted Answer

You want calendar.timegm().

>>> calendar.timegm(time.gmtime())

You can turn your string into a time tuple with time.strptime(), which returns a time tuple that you can pass to calendar.timegm():

>>> import calendar
>>> import time
>>> calendar.timegm(time.strptime('Jul 9, 2009 @ 20:02:58 UTC', '%b %d, %Y @ %H:%M:%S UTC'))

More information about calendar module here

4/2/2015 9:58:59 PM

Use the time module:

epoch_time = int(time.time())

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow