Last active
August 29, 2015 14:16
-
-
Save williballenthin/331f872cc157d64a8d53 to your computer and use it in GitHub Desktop.
parse an apache log timestamp, which looks something like `[17/Jan/2015:22:59:59 -0600]`
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
| # from: http://www.seehuhn.de/blog/52 | |
| class Timezone(datetime.tzinfo): | |
| def __init__(self, name="+0000"): | |
| self.name = name | |
| seconds = int(name[:-2])*3600+int(name[-2:])*60 | |
| self.offset = datetime.timedelta(seconds=seconds) | |
| def utcoffset(self, dt): | |
| return self.offset | |
| def dst(self, dt): | |
| return datetime.timedelta(0) | |
| def tzname(self, dt): | |
| return self.name | |
| def parse_apache_log_timestamp(ts): | |
| ts = ts.strip("[]") | |
| tt = time.strptime(ts[:-6], "%d/%b/%Y:%H:%M:%S") | |
| tt = list(tt[:6]) + [ 0, Timezone(ts[-5:]) ] | |
| d = datetime.datetime(*tt) | |
| # remove TZ offset | |
| dd = d - d.utcoffset() | |
| return dd.replace(tzinfo=None) | |
| print(parse_apache_log_timestamp("[17/Jan/2015:22:59:59 -0600]")) # --> 2015-01-18 04:59:59 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment