How can I account for period (AM/PM) with datetime.strptime?

丶灬走出姿态 提交于 2019-11-26 06:30:00

问题


Specifically I have code that simplifies to this:

from datetime import datetime
date_string = \'2009-11-29 03:17 PM\'
format = \'%Y-%m-%d %H:%M %p\'
my_date = datetime.strptime(date_string, format)

# This prints \'2009-11-29 03:17 AM\'
print my_date.strftime(format)

What gives? Does Python just ignore the period specifier when parsing dates or am I doing something stupid?


回答1:


The Python time.strftime docs say:

When used with the strptime() function, the %p directive only affects the output hour field if the %I directive is used to parse the hour.

Sure enough, changing your %H to %I makes it work.




回答2:


format = '%Y-%m-%d %H:%M %p'

The format is using %H instead of %I. Since %H is the "24-hour" format, it's likely just discarding the %p information. It works just fine if you change the %H to %I.




回答3:


You used %H (24 hour format) instead of %I (12 hour format).




回答4:


Try replacing %H (Hour on a 24-hour clock) with %I (Hour on a 12-hour clock) ?



来源:https://stackoverflow.com/questions/1759455/how-can-i-account-for-period-am-pm-with-datetime-strptime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!