IndexError:字符串索引超出范围(日历函数)



我正在尝试输出日历上的日期,例如:20121-02-02 20121-02-03 20121-02-04 20121-02-05等。我从https://www.tutorialbrain.com/python-calendar/复制了这段代码,所以我不明白为什么我得到错误。

import calendar
year = 2021
month = 2
cal_obj = calendar.Calendar(firstweekday=1)
dates = cal_obj.itermonthdays(year, month)
for i in dates:
i = str(i)
if i[6] == "2":
print(i, end="")

错误:

if i[6] == "2":
IndexError: string index out of range
Process finished with exit code 1

你的代码和他们的代码是有区别的。它很微妙,但确实存在:

你:

dates = cal_obj.itermonthdays(year, month)
^^^^ days

他们:

dates = cal_obj.itermonthdates(year, month)
^^^^^ dates

itermonthdays返回当月的天数为ints,而itermonthdates返回datetime.dates。

如果您的目标是创建日历日期列表,您也可以使用以下命令:

import pandas as pd
from datetime import datetime
datelist = list(pd.date_range(start="2021/01/01", end="2021/12/31").strftime("%Y-%m-%d"))
datelist

您可以选择任何开始日期或结束日期(如果该日期存在)

Output :  
['2021-01-01',
'2021-01-02',
'2021-01-03',
'2021-01-04',
'2021-01-05',
'2021-01-06',
'2021-01-07',
'2021-01-08',
'2021-01-09',
'2021-01-10',
'2021-01-11',
'2021-01-12',
...
'2021-12-28',
'2021-12-29',
'2021-12-30',
'2021-12-31']

似乎您是python的新手i[6]意味着列表或类列表数据类型的元素的索引。同样的事情可以通过以下方式使用datetime库来实现

import datetime
start_date = datetime.date(2021, 2, 1)  # set the start date in from of (year, month, day)
no_of_days = 30   # no of days you wanna print
day_jump = datetime.timedelta(days=1)  # No of days to jump with each iteration, defaut 1
end_date = start_date + no_of_days * day_jump # Seting up the end date
for i in range((end_date - start_date).days):
print(start_date + i * day_jump)

输出
2021-02-01
2021-02-02
2021-02-03
2021-02-04
2021-02-05
2021-02-06
2021-02-07
2021-02-08
2021-02-09
2021-02-10
2021-02-11
2021-02-12
2021-02-13
2021-02-14
2021-02-15
2021-02-16
2021-02-17
2021-02-18
2021-02-19
2021-02-20
2021-02-21
2021-02-22
2021-02-23
2021-02-24
2021-02-25
2021-02-26
2021-02-27
2021-02-28
2021-03-01
2021-03-02

最新更新