【问题标题】:IndexError: string index out of range (Calendar function)IndexError:字符串索引超出范围(日历函数)
【发布时间】:2021-12-11 02:46:03
【问题描述】:

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

【问题讨论】:

  • if 不是多余的,因为您已经将月份设置为 2?

标签: python string function calendar index-error


【解决方案1】:

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

你的:

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

他们的:

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

itermonthdays 以ints 返回月份中的天数,而itermonthdates 返回datetime.dates。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案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']
      

      【讨论】:

        猜你喜欢
        • 2021-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-25
        • 1970-01-01
        相关资源
        最近更新 更多