标签归档:strptime

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

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

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?


回答 0

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.


回答 1

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.


回答 2

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

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


回答 3

尝试将%H(24小时制)设置为%I(12小时制)。

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