Formatting RFC 822 date

Carey Evans careye at spamcop.net
Wed Apr 4 05:54:55 EDT 2001


brey at ductape.net writes:

> I'm using smtplib to send an email message, and I'd like to put a Date: line
> in the header.  However, formatting the timezone portion of the date line
> correctly seems to be a real highly non-trivial.  time.strftime only outputs
> the time zone as a string, and none of the variables in the time module are
> easy to convert to the -600 style format.

This seems fairly straightforward to me.  The following is tested with
Python 2.0 on Debian GNU/Linux unstable.

If you really can't get the timezone, use time.gmtime() instead, and
write "+0000" as the zone.

--------------------
import time

def zone822(dst):
    if dst == -1:
        return '-0000'
    else:
        offs = (time.timezone, time.altzone)[dst]
        return '%+05d' % (offs / -36)

def date822(t):
    Y,M,D,h,m,s,w,j,dst = time.localtime(t)
    weekday = ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')[w]
    month = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
             'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')[M-1]
    return '%s, %2d %s %04d %02d:%02d:%02d %s' % \
           (weekday, D, month, Y, h, m, s, zone822(dst))

-- 
	 Carey Evans  http://home.clear.net.nz/pages/c.evans/

	    "Quiet, you'll miss the humorous conclusion."



More information about the Python-list mailing list