使用AM / PM将python字符串转换为datetime obj [英] Converting python string to datetime obj with AM/PM

查看:353
本文介绍了使用AM / PM将python字符串转换为datetime obj的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

容易的问题,但这使我烦恼:

easy problem but this is bugging me:

说我有这样的字符串:

test = '2015-08-12 13:07:32'

要将其转换为日期时间对象并将其更改为AM / PM规范,这不应该吗?

To convert it into a datetime object and change it to AM/PM specification, shouldn't this work?

datetime.datetime.strptime(test, '%Y-%m-%d %I:%M:%S %p')

我遇到这样的错误:
ValueError:时间数据'2015-08-12 13:07:32'与格式'%Y-%m不匹配-%d%I:%M:%S%p'

另外,奖励积分:

如果我已经具有日期时间格式的内容,如何从该状态更改它? (如果我想将其保留为日期时间对象,而只是对其进行重新格式化以使其成为AM / PM)

If I already have something in datetime format, how do I change it from that state? (if I wanted to keep it as a datetime object but just reformat it to make it AM/PM)

推荐答案

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.

这篇关于使用AM / PM将python字符串转换为datetime obj的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆