4

I have the following python snippet:

from datetime import datetime

timestamp = '05/Jan/2015:17:47:59:000-0800'
datetime_object = datetime.strptime(timestamp, '%d/%m/%y:%H:%M:%S:%f-%Z')
print datetime_object

However when I execute the code, I'm getting the following error:

ValueError: time data '05/Jan/2015:17:47:59:000-0800' does not match format '%d/%m/%y:%H:%M:%S:%f-%Z'

what's wrong with my matching expression?

cybertextron
  • 10,547
  • 28
  • 104
  • 208

2 Answers2

6

EDIT 2: According to this post, strptime doesn't support %z (despite what the documentation suggests). To get around this, you can just ignore the timezone adjustment?:

from datetime import datetime

timestamp = '05/Jan/2015:17:47:59:000-0800'
# only take the first 24 characters of `timestamp` by using [:24]
dt_object = datetime.strptime(timestamp[:24], '%d/%b/%Y:%H:%M:%S:%f')
print(dt_object)

Gives the following output:

$ python date.py
2015-01-05 17:47:59

EDIT: Your datetime.strptime argument should be '%d/%b/%Y:%H:%M:%S:%f-%z'

With strptime(), %y refers to

Year without century as a zero-padded decimal number

I.e. 01, 99, etc.

If you want to use the full 4-digit year, you need to use %Y

Similarly, if you want to use the 3-letter month, you need to use %b, not %m

I haven't looked at the rest of the string, but there are possibly more mismatches. You can find out how each section can be defined in the table at https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

rst-2cv
  • 1,130
  • 1
  • 15
  • 31
  • That mismatch is fine... I'm more worried with the milliseconds and the timezone ... could you help me with that? – cybertextron May 26 '18 at 03:36
  • It's all listed in the table in the link I gave you – rst-2cv May 26 '18 at 03:37
  • @cybertextron edited my post to have the string of identifiers you should be using – rst-2cv May 26 '18 at 03:41
  • when I run with `timestamp='05/Jan/2015:17:47:59:000-0800'` I'm getting `ValueError: 'z' is a bad directive in format '%d/%b/%Y:%H:%M:%S:%f%z'` ... – cybertextron May 26 '18 at 03:43
  • @cybertextron I'm getting that too, looking into it. In the mean time, if you change your date string to `timestamp='05/Jan/2015:17:47:59:000-UTC'`, the following argument for `strptime` works: `%d/%b/%Y:%H:%M:%S:%f-%Z` – rst-2cv May 26 '18 at 03:44
  • 1
    @cybertextron Updated my post, I've got a solution – rst-2cv May 26 '18 at 04:36
0

And UTC offset is lowercase z.

Mulli
  • 129
  • 6
  • If I hadd `%z` I'm getting the following error: `ValueError: 'z' is a bad directive in format '%d/%b/%Y:%H:%M:%S:%f%z'` – cybertextron May 26 '18 at 03:40