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

PythonDatetimeTime

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

Use the time module:

import time    
epoch_time = int(time.time())

Solution 2 - Python

If you got here because a search engine told you this is how to get the Unix timestamp, stop reading this answer. Scroll up one.

If you want to reverse time.gmtime(), you want calendar.timegm().

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

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'))
1247169778

More information about calendar module here

Solution 3 - Python

Note that time.gmtime maps timestamp 0 to 1970-1-1 00:00:00.

In [61]: import time       
In [63]: time.gmtime(0)
Out[63]: time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)

time.mktime(time.gmtime(0)) gives you a timestamp shifted by an amount that depends on your locale, which in general may not be 0.

In [64]: time.mktime(time.gmtime(0))
Out[64]: 18000.0

The inverse of time.gmtime is calendar.timegm:

In [62]: import calendar    
In [65]: calendar.timegm(time.gmtime(0))
Out[65]: 0

Solution 4 - Python

ep = datetime.datetime(1970,1,1,0,0,0)
x = (datetime.datetime.utcnow()- ep).total_seconds()

This should be different from int(time.time()), but it is safe to use something like x % (60*60*24)

datetime — Basic date and time types:

> Unlike the time module, the datetime module does not support leap seconds.

Solution 5 - Python

t = datetime.strptime('Jul 9, 2009 @ 20:02:58 UTC',"%b %d, %Y @ %H:%M:%S %Z")

Solution 6 - Python

There are two ways, depending on your original timestamp:

mktime() and timegm()

http://docs.python.org/library/time.html

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioncalccryptoView Question on Stackoverflow
Solution 1 - PythonnarenView Answer on Stackoverflow
Solution 2 - PythonnmichaelsView Answer on Stackoverflow
Solution 3 - PythonunutbuView Answer on Stackoverflow
Solution 4 - Pythonuser3226167View Answer on Stackoverflow
Solution 5 - PythonFalmarriView Answer on Stackoverflow
Solution 6 - PythonEvan MulawskiView Answer on Stackoverflow