我在解析时间戳中的特定字符串时遇到麻烦。似乎无法正确处理上午/下午时段:
$ 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点?我在做什么错了?
答案 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)