我在解析特定字符串以获取时间戳时遇到麻烦。上午/下午时段似乎未正确处理:
$ 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点?我在做什么错?
您需要使用%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)