0

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
1
  • isn't the if redundant as you've already set the month to 2? Commented Oct 25, 2021 at 15:52

3 Answers 3

2

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

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

Seems like you are new to python i[6] means index to an element of a list or list-like data type. The same stuff can be achieved by using datetime library in the following way

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)

OUTPUT

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.