Skip to content

Instantly share code, notes, and snippets.

@williballenthin
Last active August 29, 2015 14:16
Show Gist options
  • Select an option

  • Save williballenthin/331f872cc157d64a8d53 to your computer and use it in GitHub Desktop.

Select an option

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]`
# 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