# Python Calendar Module

The `calendar` module allows you to output calendars like the Unix `cal` program, and provides additional useful functions related to the calendar. By default, these calendars have Monday as the first day of the week, and Sunday as the last (the European convention).

## Importing the Module

```python
import calendar
```

## Displaying Calendars

### Text Calendar

You can generate a plain text calendar for a specific month or year.

```python
import calendar

# Create a TextCalendar instance
c = calendar.TextCalendar(calendar.SUNDAY)

# Print a month's calendar
str_month = c.formatmonth(2023, 10)
print(str_month)
```

You can also use module-level functions for quick output.

```python
# Print the calendar for a specific month
print(calendar.month(2023, 10))

# Print the calendar for a whole year
print(calendar.calendar(2023))
```

### HTML Calendar

The module can also generate HTML calendars.

```python
import calendar

hc = calendar.HTMLCalendar(calendar.SUNDAY)
str_month = hc.formatmonth(2023, 10)
print(str_month)
```

## Iterating Over Dates

### `monthcalendar()`

Returns a matrix representing a month's calendar. Each row represents a week; days outside of the month are represented by zeros.

```python
import calendar

matrix = calendar.monthcalendar(2023, 10)
print(matrix)
# Output: [[0, 0, 0, 0, 0, 0, 1], [2, 3, 4, 5, 6, 7, 8], ...]
```

### `itermonthdates()`

Returns an iterator for the month (as `datetime.date` objects). This includes days from the previous and next months to complete the weeks.

```python
import calendar

c = calendar.Calendar()
for date in c.itermonthdates(2023, 10):
    print(date)
```

## Leap Years

### `isleap()`

Returns `True` if year is a leap year, otherwise `False`.

```python
import calendar

print(calendar.isleap(2020)) # False
print(calendar.isleap(2024)) # True
```

### `leapdays()`

Returns the number of leap years in the range [y1, y2).

```python
import calendar

print(calendar.leapdays(2000, 2025)) # Output: 7
```

## Day of the Week

### `weekday()`

Returns the day of the week (`0` is Monday) for year, month, day.

```python
import calendar

day = calendar.weekday(2023, 10, 31)
print(day) # Output: 1 (Tuesday)
```

### Day Names

You can access day and month names.

```python
import calendar

print(list(calendar.day_name))
# Output: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

print(list(calendar.month_name))
# Output: ['', 'January', 'February', ...]
```

[[programming/python/python]]