python转换日期格式pm_使用AM / PM将python字符串转换为datetime obj

easy problem but this is bugging me:

Say I have a string like this:

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

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')

I'm getting an error like this:

ValueError: time data '2015-08-12 13:07:32' does not match format '%Y-%m-%d %I:%M:%S %p'

Also, for bonus points:

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() 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 .

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

Example -

>>> 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)

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 objects internally do not store (and do not have to store) the AM/PM information, since that can be easily calculated from the hour.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值