tags:

views:

1386

answers:

3

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 ?

+2  A: 

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
Mark Roddy
Figuring out whether to use time.timezone or time.altzone is the hard part. :-)
Chris Jester-Young
For non-Python people: time.timezone is the non-DST time delta. time.altzone is the DST time delta. To my knowledge, there is no real way to tell whether a timestamp falls on DST, short of calling localtime().
Chris Jester-Young
I second Jester, i general you can't subtract with timezone since DST is not in the timezone, this will only get you localtime (without consideration to DST)
Jonke
A: 

I'm only a newbie to Python, but here's my approach.

def mkgmtime(fields):
    now = int(time.time())
    gmt = list(time.gmtime(now))
    gmt[8] = time.localtime(now).tm_isdst
    disp = now - time.mktime(tuple(gmt))
    return disp + time.mktime(fields)

There, my proposed name for the function too. :-) It's important to recalculate disp every time, in case the daylight-savings value changes or the like. (The conversion back to tuple is required for Jython. CPython doesn't seem to require it.)

This is super ick, because time.gmtime sets the DST flag to false, always. I hate the code, though. There's got to be a better way to do it. And there are probably some corner cases that I haven't got, yet.

Chris Jester-Young
+7  A: 

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.

Tom