将12小时时间字符串转换为日期时间或时间
问题内容:
我一直在尝试使用time.strptime(string1,'%H:%M')
,但没有成功
我如何获得以下信息:
Input Output
3:14AM -> 03:14
9:33PM -> 21:33
12:21AM -> 00:21
12:15PM -> 12:15
问题答案:
可使用%I
12小时,并%p
用于am
或pm
如下:
from datetime import datetime
for t in ["3:14AM", "9:33PM", "12:21AM", "12:15PM"]:
print(datetime.strptime(t, '%I:%M%p').strftime("%H:%M"))
提供以下输出:
03:14
21:33
00:21
12:15
使用的格式记录在strftime()和strptime()中