0

Using the following code I want to convert the input date and time to epoch. The problem is I get an epoch output, but when I test it via conversion online (http://www.epochconverter.com/), the epoch does not translate to the date and time I input:

date_time2 = '09.03.1999' + " " + "13:44:17.000000"
pattern2 = '%d.%m.%Y %H:%M:%S.%f'
epoch2 = int(time.mktime(time.strptime(date_time2, pattern2)))
print epoch2
martineau
  • 119,623
  • 25
  • 170
  • 301
user3498593
  • 113
  • 1
  • 1
  • 11

2 Answers2

1

What is happening here:

  • time.strptime produces a time.struct_time which closely mirrors C's tm struct;
  • The documentation of time.mktime is then fairly clear that it produces a local time from a struct_time, not a GMT time.

So instead you need a function that converts your struct_time into a GMT time. Such a function is hidden away a bit in python, in the calendar module.

Try instead:

date_time2 = '09.03.1999' + " " + "13:44:17.000000"
pattern2 = '%d.%m.%Y %H:%M:%S.%f'

# get a time structure
tm = time.strptime(date_time2, pattern2)

# convert to gmt
gmt_epoch = int(calendar.timegm(tm))

In this case we end up with:

>>> gmt_epoch
920987057

Plugging that into the website you've given produces that this is GMT: Tue, 09 Mar 1999 13:44:17 GMT

donkopotamus
  • 22,114
  • 2
  • 48
  • 60
  • Thanks. What additional modules do I need to import for this to work? I'm getting 'time.struct_time' object has no attribute 'tm_gmtoff' error when I run it. I'm already importing: `from datetime import datetime as dt,datetime,timedelta import time from datetime import datetime from dateutil import tz import pytz ` – user3498593 Jul 25 '16 at 02:01
  • I'm using Python 2.7 by the way – user3498593 Jul 25 '16 at 02:12
  • `tm_gmtoff` is available in Python 3.3 and greater: https://docs.python.org/3/library/time.html#time.struct_time Please see my answer. – mechanical_meat Jul 25 '16 at 02:53
  • 1
    @user3498593 I've modified the answer so it should work on 2.7. I tried to keep this answer strictly within the standard library ... but honestly, if you want to deal with times properly and easily you really should consider installing `pytz` as @bernie suggests – donkopotamus Jul 25 '16 at 04:50
1

(I already upvoted @donkopotamus' answer here: https://stackoverflow.com/a/38558696/42346)

Using this answer: https://stackoverflow.com/a/19527596/42346 we can see how you can convert your local time to GMT. This requires pytz.

import datetime as dt 
import pytz

naive_date = dt.datetime.strptime('09.03.1999' + " " + "13:44:17.000000", 
                                  '%d.%m.%Y %H:%M:%S.%f')
localtz = pytz.timezone('Hongkong')
date_aware = localtz.localize(naive_date,is_dst=None)
utc_date = date_aware.astimezone(pytz.utc)
int(time.mktime(utc_date.utctimetuple()))

Result:

920987057

enter image description here

Community
  • 1
  • 1
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223