-1

I am having a problem with parsing time string to datetime. A snip of my code is as follows:

 datetime.datetime.strptime('16/Sep/2017:00:00:00 +0000', '%d/%b/%Y:%M:%H:%S %z')

I am getting the following error:

 ValueError: 'z' is a bad directive in format '%d/%b/%Y:%M:%H:%S %z'

I am on Python 2.7.10.

Please come up with simple solution, instead complicated code as I am running this to on a log file having millions of rows. Thanks.

Solution to this particular problem is not found.

ituring
  • 11
  • 5
  • Possible duplicate of [Convert timestamps with offset to datetime obj using strptime](https://stackoverflow.com/questions/12281975/convert-timestamps-with-offset-to-datetime-obj-using-strptime) – glibdud Oct 03 '17 at 13:45

2 Answers2

1

Solved with using dateutil module. Here is my solution:

from dateutil.parser import parse
parse('16/Sep/2017:00:00:00 +0000'.replace(':', ' ',1))
datetime.datetime(2015, 6, 24, 0, 1, 3, tzinfo=tzoffset(None, 7200))

There is bug in Python 2.7.* regarding %z directive. Hope they will fix it one day.

ituring
  • 11
  • 5
  • It's not a bug, it's a feature that wasn't implemented until [3.2](https://docs.python.org/dev/whatsnew/3.2.html#datetime-and-time). – glibdud Oct 03 '17 at 14:07
  • It's a bug in the Python 2 docs then because `%z` is listed as being accepted. https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior – richard_ Feb 05 '19 at 15:42
0

It looks as if strptime doesn't always support %z. Python appears to just call the C function, and strptime doesn't support %z on your platform.

Note: from Python 3.2 onwards it will always work.

Gowtham Balusamy
  • 728
  • 10
  • 22