How to get the seconds since epoch from the time + date output of gmtime()?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Droplet of life
--
Chapters
00:00 How To Get The Seconds Since Epoch From The Time + Date Output Of Gmtime()?
00:32 Accepted Answer Score 156
01:06 Answer 2 Score 5
01:12 Answer 3 Score 10
01:45 Answer 4 Score 873
01:53 Thank you
--
Full question
https://stackoverflow.com/questions/4548...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #datetime #time
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Droplet of life
--
Chapters
00:00 How To Get The Seconds Since Epoch From The Time + Date Output Of Gmtime()?
00:32 Accepted Answer Score 156
01:06 Answer 2 Score 5
01:12 Answer 3 Score 10
01:45 Answer 4 Score 873
01:53 Thank you
--
Full question
https://stackoverflow.com/questions/4548...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #datetime #time
#avk47
ANSWER 1
Score 873
Use the time module:
import time
epoch_time = int(time.time())
ACCEPTED ANSWER
Score 156
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
ANSWER 3
Score 10
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
ANSWER 4
Score 5
t = datetime.strptime('Jul 9, 2009 @ 20:02:58 UTC',"%b %d, %Y @ %H:%M:%S %Z")