mktime() like function to produce GMT?

Mark Nottingham mnot at pobox.com
Fri Apr 30 20:18:34 EDT 1999


Marc-Andre: Thanks. I'll take a look at it (shame it's not in the std
library).

Guido: I had tried a similar approach;

date = mktime(rfc822.parsedate(datestring)) - time.timezone

Neither this or mktime_tz will work; both will sometimes return dates that
are off by one hour, depending on dst. I think this is because I'm parsing
dates that may fall at any arbitrary time in the past, when the machine
doesn't (AFAIK) have perfect knowledge about dst.

Ultimately, I'm trying to parse a UTC datestring (HTTP Last-Modified header
in one of the three accepted formats) into a rfc1123-format datestring (as
well as a number to play with); the date should never have to even know
about localtime (which is causing all of the problems, in this case). With
either the above solution or mktime_tz(), some dates will parse back to
themselves, while others will have a one hour offset.

One such date (in my tz - aust eastern) is "Tue, 18 Mar 1997 05:32:18 GMT"
which, after munging, will think it's 04:32:18.

I'm testing with:

#!/usr/bin/env python
import sys, time, rfc822
g = list(rfc822.parsedate_tz(sys.argv[1]))
g[9] = 0
date = rfc822.mktime_tz(tuple(g))
print time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(date))



> Huh?  The C library function gmtime() *returns* a time tuple in UTC
> (the polutically correct name for GMT).
>
> 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






More information about the Python-list mailing list