0

I am trying to convert a time stamp of the format 20151021|133102[-0400/1] into an epoch time.

I want the code to run regardless of the native timezone of the machine it is running on, and be DST aware so the code will run over the switch to/from DST. I need the code to run under Python 2.7.x (ideally using only standard library modules so the code is portable.)

After wasting the afternoon googling, the best I have been able to do is:

time.mktime(time.strptime('20151021|133102','%Y%m%d|%H%M%S'))`

which does not allow me to incorporate either the offset, or the daylight savings flag.

I also tried the following:

time.mktime(time.strptime('20151021|133102-4000','%Y%m%d|%H%M%S%z'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/_strptime.py", line 467, in _strptime_time
    return _strptime(data_string, format)[0]
  File "/usr/lib/python2.7/_strptime.py", line 317, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y%m%d|%H%M%S%z'

but it seems that strptime does not allow the offset.

strptime does support:

time.mktime(time.strptime('20151021|133102EDT','%Y%m%d|%H%M%S%Z'))

but this means that I need to somehow convert the offset into a timezone abbreviation which seems sort of stupid--and might create an error depending on where the code is run.

I can't believe this isn't more straight forward given routine this problem should be. Any assistance would be much appreciated.

MattDMo
  • 100,794
  • 21
  • 241
  • 231
user73383
  • 89
  • 1
  • 7

3 Answers3

0

There are two steps:

I want the code to run regardless of the native timezone of the machine it is running on

time.mktime() expects local time as an input. Don't use it if the input time string does not represent local time. You also shouldn't use it if the time string has the utc offset (mktime() may produce a wrong result for ambiguous times or past/future dates).

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
-1

First off you are identifying the numbers as a string. What I did was identify the string as an integer and then use datatime to convert into epoche time.

You'll need to remove the symbols not identified as an integer to have the following number listed above but the code below works for me on python 2.7

import datetime conversion = datetime.datetime.fromtimestamp(int("20151021")).strftime('%Y-%m-%d %H:%M:%S') print (conversion)

Rob
  • 177
  • 1
  • 5
-1

Weird. Works in Python3, but not Python2

>>> time.mktime(time.strptime('20151021|133102-0400', '%Y%m%d|%H%M%S%z'))
1445452262.0
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Thanks for the reply I was running Python 2.7.9 which is the latest 2.7 branch. Don't want to move to 3.x since so many important libraries are still 2.7.x as are many small systems. – user73383 Oct 21 '15 at 22:55