python - 如何使用 strftime 计算期间 (AM/PM)?

具体来说,我有代码可以简化为:

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)

什么给了? Python 在解析日期时是否只是忽略了句点说明符,还是我在做一些愚蠢的事情?

最佳答案

python time.strftime docs说:

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.

果然,把你的 %H 改成 %I 就可以了。

https://stackoverflow.com/questions/1759455/

相关文章:

linux - 解释段错误消息

python - 如何在 Linux 上使用 Python 导出

python - 如何将一列中的文本拆分为多行

python - 如何获取python列表的第n个元素或默认值(如果不可用)

linux - 设置 Apache 用户的 umask

python - 通过索引访问 collections.OrderedDict 中的项目

linux - 在 Linux 中编译/运行汇编程序?

python - 我可以使用 `pip` 而不是 `easy_install` 进行 `python

linux - 如何在 Ubuntu 中添加用户?

python - Matplotlib 中的 bin 大小(直方图)