Reputation: 329
I'm having trouble parsing a specific string for a timestamp. The am/pm period doesn't seem to be processed properly:
$ python --version
Python 2.7.17
$ cat tmp/time_problem
#! /usr/bin/env python
import datetime
timestamp_string = '2019-10-22, 3:48:35 PM'
timestamp = datetime.datetime.strptime(timestamp_string, '%Y-%m-%d, %H:%M:%S %p')
print repr(timestamp)
$ tmp/time_problem
datetime.datetime(2019, 10, 22, 3, 48, 35)
$
Why isn't the hour 15 rather than 3? What am I doing wrong?
Upvotes: 1
Views: 98
Reputation: 74645
You need to use %I
and not %H
for the hour.
import datetime
timestamp_string = '2019-10-22, 3:48:35 PM'
timestamp = datetime.datetime.strptime(timestamp_string, '%Y-%m-%d, %H:%M:%S %p')
print repr(timestamp)
# datetime.datetime(2019, 10, 22, 3, 48, 35)
timestamp_string = '2019-10-22, 3:48:35 PM'
timestamp = datetime.datetime.strptime(timestamp_string, '%Y-%m-%d, %I:%M:%S %p')
print repr(timestamp)
# datetime.datetime(2019, 10, 22, 15, 48, 35)
Upvotes: 2