如何在 Python 的时间戳期间正确解析 AM/PM?
How to properly parse AM/PM in timestamp's period in Python?
我在解析时间戳的特定字符串时遇到问题。 am/pm 句号似乎处理不当:
$ 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)
我在解析时间戳的特定字符串时遇到问题。 am/pm 句号似乎处理不当:
$ 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)