且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用AM / PM将python字符串转换为datetime obj

更新时间:2023-10-22 14:19:28

datetime.strptime()用于将字符串转换为datetime对象,当使用 strptime()时,必须指定正确的

datetime.strptime() is used for converting a string to a datetime object , when using strptime() you have to specify the correct format in which the date/time in the string exists .

在您的情况下,格式应为-'%Y-%m-%d %H:%M:%S'

In your case the format should be - '%Y-%m-%d %H:%M:%S' .

示例-

>>> test = '2015-08-12 13:07:32'
>>> import datetime
>>> datetime.datetime.strptime(test, '%Y-%m-%d %H:%M:%S')
datetime.datetime(2015, 8, 12, 13, 7, 32)






如果您真正想要的是日期时间作为a带有 AM / PM 的字符串,那么您需要使用 strftime()将其转换回具有以下格式的字符串您希望在这种情况下,格式为-'%Y-%m-%d%I:%M:%S%p'。示例-


If what you really want is the date-time back as a string with the AM/PM , then you need to use strftime() to convert it back to string with the format you want, in this case the format would be - '%Y-%m-%d %I:%M:%S %p' . Example -

>>> datetime.datetime.strptime(test, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %I:%M:%S %p')
'2015-08-12 01:07:32 PM'






datetime 对象内部不存储(也不必存储)AM / PM信息,因为可以从小时轻松计算


datetime objects internally do not store (and do not have to store) the AM/PM information, since that can be easily calculated from the hour.