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

2024-10-03 09:10:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试输出日历上的日期,例如:2021-02-02 2021-02-03 2021-02-04 2021-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

Tags: 代码httpsimportcomobjifwww错误
3条回答

如果您的目标是创建日历日期列表,则还可以使用以下选项:

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']

您的代码和他们的代码之间存在差异。这很微妙,但它就在那里:

你的:

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

他们的:

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

^{}ints的形式返回月份的天数,而^{}返回^{}s

似乎您是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

相关问题 更多 >