Skip to content

Instantly share code, notes, and snippets.

@RichardHyde
Last active February 16, 2016 11:06
Show Gist options
  • Save RichardHyde/072b9902efce87947c9e to your computer and use it in GitHub Desktop.
Save RichardHyde/072b9902efce87947c9e to your computer and use it in GitHub Desktop.
Parse RFC2822 date strings into datetime object
class FixedOffset(tzinfo):
"""Fixed offset in minutes east from UTC."""
def __init__(self, offset, name):
self.__offset = timedelta(minutes=offset)
self.__name = name
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return ZERO
def parseRFC2822Date(dateString):
result = None
try:
result = datetime.strptime(dateString, "%a, %d %b %Y %H:%M:%S %Z")
return result
except:
pass
try:
result = datetime.strptime(dateString[0:-6], "%a, %d %b %Y %H:%M:%S")
offset = int(dateString[-6:])
if (offset <> 0):
offset = int(offset/100) * 60 + (int(dateString[-2:]))
result = result.replace(tzinfo=FixedOffset(offset, dateString[-6:]))
except:
print "Date parse error"
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment