mktime() like function to produce GMT?

M.-A. Lemburg mal at lemburg.com
Mon May 3 04:39:15 EDT 1999


Guido van Rossum wrote:
> 
> > Mark Nottingham wrote:
> > >
> > > I need a function to produce a Unix epoch time from a time tuple, a la
> > > time.mktime(). Problem is, mktime() gives you the tuple in localtime, which
> > > is dangerous if you're dealing with GMT times in the past (like in the
> > > HTTP).
> > >
> > > Is there a function that will make a GMT epoch time straight from a time
> > > tuple?
> 
> "M.-A. Lemburg" <mal at lemburg.com> replies:
> 
> > On some platforms there is gmtime() which does exactly this.

I meant timegm(), sorry.

> > It's available through mxDateTime, BTW, which also offers a
> > work-around solution for those platforms where it is not
> > available. See the Python Pages below.
> 
> Huh?  The C library function gmtime() *returns* a time tuple in UTC
> (the polutically correct name for GMT).

See above.

> The standard way to use mktime() with a UTC is to add or subtract the
> timezone offset (I admit I can never remember which :-) and force the
> DST flag off.
> 
> The following function in rfc822 may be helpful (it takes a 10-tuple
> whose last item is the tz offset; set this to 0 for UTC):
> 
> def mktime_tz(data):
>     """Turn a 10-tuple as returned by parsedate_tz() into a UTC timestamp."""
>     if data[9] is None:
>         # No zone info, so localtime is better assumption than GMT
>         return time.mktime(data[:8] + (-1,))
>     else:
>         t = time.mktime(data[:8] + (0,))
>         return t - data[9] - time.timezone

This doesn't always work. For one, time.timezone is set at
module init time and does not necessarily apply to the UTC
offset (depending on the platform). And second, mktime()
with DST set to 0 will not return a UTC time value on all
platforms: some implementations simply ignore the value
and recalculate it depending on the local time broken
down values.

I've had much trouble with this in mxDateTime, but finally found
a rather well working trick that only relies on mktime()
producing correct local time values.

-- 
Marc-Andre Lemburg
______________________________________________________________________
Y2000:                                            Y2000: 242 days left
Business:                                      http://www.lemburg.com/
Python Pages:                 http://starship.python.net/crew/lemburg/





More information about the Python-list mailing list