Created
June 8, 2011 15:19
-
-
Save sbp/1014626 to your computer and use it in GitHub Desktop.
Parse a datetime with a timezone in python, 2.4 compatible
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
| #!/usr/bin/env python | |
| import time, calendar, datetime | |
| input = '2011-05-26T16:02:59.199400+00:00' | |
| def dttz(input): | |
| if '+' in input: | |
| return input.split('+', 1) | |
| else: return input, None | |
| def timezone(tz): | |
| sign, offset = tz[0], tz[1:] | |
| hours, minutes = tuple([int(n) for n in offset.split(':')]) | |
| minutes += hours * 60 | |
| if sign == '-': | |
| minutes = -minutes | |
| class TimeZone(datetime.tzinfo): | |
| def utcoffset(self, dt): | |
| return datetime.timedelta(minutes=minutes) | |
| def dst(self, dt): | |
| return datetime.timedelta(0) | |
| return TimeZone() | |
| dt, tz = dttz(input) | |
| tz = timezone(tz) | |
| if '.' in dt: | |
| dt = dt.split('.', 1)[0] | |
| then = time.strptime(dt, '%Y-%m-%dT%H:%M:%S') | |
| then = datetime.datetime.utcfromtimestamp(calendar.timegm(then)) | |
| then.replace(tzinfo=tz) | |
| now = datetime.datetime.utcnow() | |
| td = (now - then) | |
| inner = (td.seconds + td.days * 24 * 3600) | |
| seconds = (td.microseconds + inner * 10**6) / 10**6 | |
| minutes = float(seconds) / 60 | |
| print minutes < 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment