如何在Python的时间戳期间正确解析AM / PM?

时间:2019-11-20 11:51:56

标签: python strptime

我在解析时间戳中的特定字符串时遇到麻烦。似乎无法正确处理上午/下午时段:

$ 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)
$

为什么小时不是15点而是3点?我在做什么错了?

1 个答案:

答案 0 :(得分:2)

您需要每小时使用%I而不是%H

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)