Python datetime to RFC2822 Date

Oct 15, 2009 10:42


Format a Python datetime as a string according to RFC 2822 section 3.3 respecting timezone. Adapted from Python's email.utils.formatdate. As a handy companion, dateutil.parser.parse works quite nicely for parsing them.

def formatrfc2822datetime(value=None, usegmt=False): """Returns a date string as specified by RFC 2822 section 3.3., e.g.:              Fri, 09 Nov 2001 01:08:47 +0900              Optional value may be a datetime value. Timezone is respected.     """ # Note: we cannot use strftime() because that honors the locale and RFC # 2822 requires that day and month names be the English abbreviations. if value is None: value = datetime.datetime.today() if usegmt: # Convert to UTC/GMT value = value - value.utcoffset() zone = 'GMT' else: offset = value.utcoffset().seconds / 60 # RFC 2822 3.3.: The form "+0000" SHOULD be used to indicate a # time zone at Universal Time. zone = '%s%02d%02d' % (offset < 0 and '-' or '+', offset // 60, offset % 60) return '%s, %02d %s %04d %02d:%02d:%02d %s' % ( ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][value.date().weekday()], value.day, ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][value.month - 1], value.year, value.hour, value.minute, value.second, zone)

python, code, snippet

Previous post Next post
Up