rfc822 date header

Chris Lawrence quango at watervalley.net
Tue Apr 13 05:41:14 EDT 1999


On Tue, 13 Apr 1999 07:39:45 GMT, M.-A. Lemburg <mal at lemburg.com> wrote:
>Jeff Bauer wrote:
>> 
>> Is there a reasonably bulletproof way to generate an
>> rfc822-compliant date header using the time module?
>> 
>> The reason I ask is I recall a number of subtle
>> errors in this regard, reported by Chris Lawrence,
>> among others.

[Eeek!  I'm famous!]

>According to the RFC, time.ctime() should do the trick...
>but it's probably locale aware which the RFC doesn't account
>for.

time.ctime() will throw you off (it will generate Unix timestamps, which are
decidedly non-RFC-compliant in any number of ways).  Try:

time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(timeval))

where timeval is a time.time() result.  If you already have the tuple form,
you may need to coax it into gmt-relative tuple form first (see the tz-aware
functions in rfc822).  Actually, here you're getting a GMT RFC-compliant
header, which is a subset of the universe of allowed headers, but if you're
dumping HTTP output this is what you need.

Cheap hack for other timezones (untested, ugly, but probably right):

ttuple = time.localtime(timeval)
x = time.strftime('%a, %d %b %Y %H:%M:%S ', ttuple)
if ttuple[8] == 1:
    x = x + ('%04d' % (-time.altzone))
else:
    x = x + ('%04d' % (-time.timezone))

Note that locales will screw up the %a (weekday) and make it
non-RFC-compliant (though whether anything in the real world will CARE is
another question entirely). You may need to bracket this with some
locale.setlocale() calls if you're using locale != "C".

Incidentally, the locale issue even affects GNU date.  Try 'LC_ALL=fr_FR
date --rfc --utc' sometime on Linux ;-)  I made a patch but dunno if it ever
made it upstream...

The "subtle errors" were mainly in parsing the damn things, and in Linux's
implementation of the time functions in libc6 (which drove me crazy until I
finally figured out what was going on a few weeks ago ;-).


Chris, exploring the minutae of the topic (as per clp tradition)
-- 
=============================================================================
|          Chris Lawrence         |       Get your Debian 2.1 CD-ROMs       |
|     <quango at watervalley.net>    |        http://www.lordsutch.com/        |
|                                 |                                         |
|     Grad Student, Pol. Sci.     |     Do you want your bank to snoop?     |
|    University of Mississippi    |    http://www.defendyourprivacy.com/    |
=============================================================================




More information about the Python-list mailing list