Home > Net >  IndexError: string index out of range (Calendar function)
IndexError: string index out of range (Calendar function)

Time:10-25

I am trying to output the days on my calendar, something like: 2021-02-02 2021-02-03 2021-02-04 2021-02-05 etc. I copied this code from https://www.tutorialbrain.com/python-calendar/ so I don't understand why I get the error.

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="")

Error:

    if i[6] == "2":
IndexError: string index out of range

Process finished with exit code 1

CodePudding user response:

There is a difference between your code and their code. It's very subtle:

Yours:

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

Theirs:

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

itermonthdays returns the days of the month as ints, while itermonthdates returns datetime.dates.

CodePudding user response:

If your goal is to create a list of date of the calendar, you can use the following aswell :

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

You can choose any start date or end date (if that date exists)

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