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

问题描述 投票:1回答:1

我在解析特定字符串以获取时间戳时遇到麻烦。上午/下午时段似乎未正确处理:

$ 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点?我在做什么错?

python strptime
1个回答
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)
© www.soinside.com 2019 - 2024. All rights reserved.