0

I have the following Python code:

import json
import fileinput
import time

ts_pattern  = '[%d/%b/%Y:%H:%M:%S +0000]'

for line in fileinput.input():
    json_data = json.loads(line)
    etime = int(time.mktime(time.strptime(json_data['time_local'], ts_pattern)))
    print etime

I have made a mistake, it appears. For example, in the JSON that I'm reading, time_local is [06/Oct/2015:15:29:35 +0000]. My script outputs 1444166975 as the result. However, that is not correct, so far as I can see:

$ date -ud @1444166975
Tue Oct  6 21:29:35 UTC 2015

Having the linux date command do the conversion back gives:

$ date +%s -ud "06-Oct-2015 15:29:35 +0000"
1444145375

So far as I understand (which could easily be wrong...), I want the output to be in GMT in order for the conversion to epoch to be correct. What am I missing?

Andrew
  • 475
  • 4
  • 15

1 Answers1

2

Don't use time.mktime() with UTC time. It accepts local time and therefore your code is wrong if your local timezone is not UTC.

Use calendar.timegm() instead:

#!/usr/bin/env python
import time
from calendar import timegm

tt = time.strptime('[06/Oct/2015:15:29:35 +0000]',
                   '[%d/%b/%Y:%H:%M:%S +0000]')
print(timegm(tt))  # -> 1444145375

See Converting datetime.date to UTC timestamp in Python

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
  • I always like the "How do I...?", "You don't" posts, as they seem to reveal new things about a language. That worked. Thank you very much. – Andrew Oct 15 '15 at 20:27