如何使用 strftime 计算期间 (AM/PM)? [英] How can I account for period (AM/PM) using strftime?

查看:28
本文介绍了如何使用 strftime 计算期间 (AM/PM)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

特别是我有代码可以简化为:

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)

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

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

推荐答案

Python time.strftime 文档 说:

The Python time.strftime docs say:

与 strptime() 函数一起使用时,仅 %p 指令如果 %I 指令用于解析,则影响输出小时字段小时.

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 就可以了.

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

这篇关于如何使用 strftime 计算期间 (AM/PM)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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