John
John

Reputation: 329

How to properly parse AM/PM in timestamp's period in Python?

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

Answers (1)

Dan D.
Dan D.

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

Related Questions