如何使用 strftime 计算时间段(AM/PM)?

发布于 2024-08-11 09:52:41 字数 313 浏览 3 评论 0原文

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

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 在解析日期时是否只是忽略句点说明符,还是我在做一些愚蠢的事情?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

那一片橙海, 2024-08-18 09:52:41

Python time.strftime 文档说:

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

果然,将 %H 更改为 %I 就可以了。

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.

清风疏影 2024-08-18 09:52:41
format = '%Y-%m-%d %H:%M %p'

格式使用 %H 而不是 %I。由于 %H 是“24 小时”格式,因此很可能只是丢弃 %p 信息。如果将 %H 更改为 %I,效果就很好。

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.

A君 2024-08-18 09:52:41

您使用了 %H(24 小时格式)而不是 %I(12 小时格式)。

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

眼眸 2024-08-18 09:52:41

尝试将 %I 替换为 %H

from datetime import datetime
print(datetime.today().strftime("%H:%M %p")) # 15:31 AM

成为

from datetime import datetime
print(datetime.today().strftime("%I:%M %p")) # 03:31 AM

Try replacing %I with %H.

from datetime import datetime
print(datetime.today().strftime("%H:%M %p")) # 15:31 AM

Becomes

from datetime import datetime
print(datetime.today().strftime("%I:%M %p")) # 03:31 AM
陈甜 2024-08-18 09:52:41

尝试将 %H(24 小时制的小时)替换为 %I(12 小时制的小时)?

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文