Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an inverse function for time.gmtime() that parses a UTC tuple to seconds since the epoch?

Tags:

python's time module seems a little haphazard. For example, here is a list of methods in there, from the docstring:

time() -- return current time in seconds since the Epoch as a float clock() -- return CPU time since process start as a float sleep() -- delay for a number of seconds given as a float gmtime() -- convert seconds since Epoch to UTC tuple localtime() -- convert seconds since Epoch to local time tuple asctime() -- convert time tuple to string ctime() -- convert time in seconds to string mktime() -- convert local time tuple to seconds since Epoch strftime() -- convert time tuple to string according to format specification strptime() -- parse string to time tuple according to format specification tzset() -- change the local timezone 

Looking at localtime() and its inverse mktime(), why is there no inverse for gmtime() ?

Bonus questions: what would you name the method ? How would you implement it ?

like image 505
Thomas Vander Stichele Avatar asked Sep 24 '08 21:09

Thomas Vander Stichele


People also ask

What is time Gmtime in Python?

Python time gmtime() Method Pythom time method gmtime() converts a time expressed in seconds since the epoch to a struct_time in UTC in which the dst flag is always zero. If secs is not provided or None, the current time as returned by time() is used.

Which of the following time function in python time module can be used to display time in variety of formats?

strftime() function converts a tuple or struct_time representing a time as returned by gmtime() or localtime() to a string as specified by the format argument.


2 Answers

There is actually an inverse function, but for some bizarre reason, it's in the calendar module: calendar.timegm(). I listed the functions in this answer.

like image 82
Tom Avatar answered Oct 20 '22 04:10

Tom


I always thought the time and datetime modules were a little incoherent. Anyways, here's the inverse of mktime

import time def mkgmtime(t):     """Convert UTC tuple to seconds since Epoch"""     return time.mktime(t)-time.timezone 
like image 45
Mark Roddy Avatar answered Oct 20 '22 05:10

Mark Roddy