这里有些东西看起来有点傻:datetime.strptime()
当我只是手动创建一个列表( months = ['January','February']
)时很高兴接受月份名称的迭代列表,但当我迭代由 calendar.month_name
创建的月份列表时则不会即使两者都返回 <type 'str'>
损坏的代码:
import datetime
import calendar
for month in calendar.month_name:
print datetime.datetime.strptime(month,"%B")
错误:
ValueError: time data '' does not match format '%B'
工作代码:
import datetime
months = ['January','February','March']
for month in months:
print datetime.datetime.strptime(month,"%B")
结果:
1900-01-01 00:00:00
1900-02-01 00:00:00
1900-03-01 00:00:00
这是怎么回事?这是 python 的行为吗 for
循环我不熟悉?
最佳答案
尝试执行 print( list(calendar.month_name) )
很快就会明白失败的原因......(主要是因为产生的第一个元素是一个空字符串)。请注意,产生的第一个月是空字符串的原因是因为他们希望 month_names[1]
与 January
对应,这是常见的约定(参见 documentation )
你可以做这样的事情:
a = list( calendar.month_names )[1:]
或者这至少在 Cpython 中也有效(尽管在文档中不清楚是否应该这样做):
a = calendar.month_names[1:]
关于python - calendar.month_name 的迭代不能被 strptime() 解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11675550/