Last active
February 16, 2016 11:06
-
-
Save RichardHyde/072b9902efce87947c9e to your computer and use it in GitHub Desktop.
Parse RFC2822 date strings into datetime object
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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