Python. Flipping Calendars.
Tags: python, programming, howto, tutorial
Published: 2024-05-17 00:47:17

In the modern digital era, calendars have become indispensable tools that help us organize our lives, manage time, and stay abreast of important events and appointments. While traditional paper calendars have served us well for many years, digital calendars offer a level of convenience and flexibility that is hard to surpass.

In this article, through a series of Python code examples, I will delve into the intricacies of calendar creation, covering fundamental concepts. Let's embark on this exciting programming adventure and unlock the potential of Python in calendar construction!

Here's the Python code that prints the calendar for the current month:

```
import calendar

# Get the current year and month
year = calendar.datetime.datetime.now().year
month = calendar.datetime.datetime.now().month

# Create a calendar object
cal = calendar.TextCalendar(calendar.SUNDAY)

# Print the calendar for the current month
print(cal.formatmonth(year, month))
```

Example of how it works.

```
dmi@dmi-laptop:~/my_python$ python3 my_calendar.py 
      May 2024
Su Mo Tu We Th Fr Sa
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

dmi@dmi-laptop:~/my_python$ 
```

Here's the modified Python code to print the calendars for the current, previous, and next months:

```
import calendar

# Get the current year and month
current_year = calendar.datetime.datetime.now().year
current_month = calendar.datetime.datetime.now().month

# Create a calendar object
cal = calendar.TextCalendar(calendar.SUNDAY)

# Print the calendars for the current, previous, and next months
for month_shift in range(-1, 2):
    year = current_year
    month = current_month + month_shift
    if month <= 0:
        month += 12
        year -= 1
    elif month > 12:
        month -= 12
        year += 1
    print(f"Calendar for {calendar.month_name[month]} {year}:")
    print(cal.formatmonth(year, month))
    print()
```

This code iterates over the current, previous, and next months, adjusts the year if necessary, and then prints the calendar for each month.

Example of how it works.

```
dmi@dmi-laptop:~/my_python$ python3 my_calendar.py 
Calendar for April 2024:
     April 2024
Su Mo Tu We Th Fr Sa
    1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30


Calendar for May 2024:
      May 2024
Su Mo Tu We Th Fr Sa
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31


Calendar for June 2024:
     June 2024
Su Mo Tu We Th Fr Sa
                   1
 2  3  4  5  6  7  8
 9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30

dmi@dmi-laptop:~/my_python$ 
```

Here's the Python code to print the calendar for all months of the current year.

This code iterates over all the months of the current year and prints the calendar for each month.

```
import calendar

# Get the current year
current_year = calendar.datetime.datetime.now().year

# Create a calendar object
cal = calendar.TextCalendar(calendar.SUNDAY)

# Print the calendars for all months of the current year
for month in range(1, 13):
    print(f"Calendar for {calendar.month_name[month]} {current_year}:")
    print(cal.formatmonth(current_year, month))
    print()
```

This code prints the calendar for the current week, starting Monday and ending Sunday, without using the calendar module.

```
from datetime import datetime, timedelta

def print_current_week_calendar():
    # Get the current date
    today = datetime.now()

    # Determine the start and end of the current week
    start_of_week = today - timedelta(days=today.weekday())
    end_of_week = start_of_week + timedelta(days=6)

    # Print the calendar for the current week
    print("Calendar for the current week:")
    current_date = start_of_week
    while current_date <= end_of_week:
        print(current_date.strftime("%A, %Y-%m-%d"))
        current_date += timedelta(days=1)

# Call the function to print the calendar for the current week
print_current_week_calendar()
```

Example of how it works.

```
Calendar for the current week:
Monday, 2024-05-13
Tuesday, 2024-05-14
Wednesday, 2024-05-15
Thursday, 2024-05-16
Friday, 2024-05-17
Saturday, 2024-05-18
Sunday, 2024-05-19
```

This code prints the calendar for the current week, starting from Monday and ending on Sunday, and then the calendar for the next week, also from Monday to Sunday. It uses the datetime module to work with dates and timedelta to calculate the start and end of the weeks. Comments in the code help understand the steps taken to determine and print each week.

```
from datetime import datetime, timedelta

def print_week_calendar(start_date, end_date):
    # Print the calendar for the week
    print("Calendar for the week:")
    current_date = start_date
    while current_date <= end_date:
        print(current_date.strftime("%A, %Y-%m-%d"))
        current_date += timedelta(days=1)

# Get the current date
current_date = datetime.now()

# Determine the start and end of the current week
start_of_current_week = current_date - timedelta(days=current_date.weekday())
end_of_current_week = start_of_current_week + timedelta(days=6)  # Sunday

# Print the calendar for the current week
print("\nCurrent Week:")
print_week_calendar(start_of_current_week, end_of_current_week)

# Determine the start and end of the next week
next_week_start = end_of_current_week + timedelta(days=1)  # Monday of the next week
next_week_end = next_week_start + timedelta(days=6)  # Sunday of the next week

# Print the calendar for the next week
print("\nNext Week:")
print_week_calendar(next_week_start, next_week_end)
```

Example of how it works.

```
dmi@dmi-laptop:~/my_python$ python3 my_calendar.py 

Current Week:
Calendar for the week:
Monday, 2024-05-13
Tuesday, 2024-05-14
Wednesday, 2024-05-15
Thursday, 2024-05-16
Friday, 2024-05-17
Saturday, 2024-05-18
Sunday, 2024-05-19

Next Week:
Calendar for the week:
Monday, 2024-05-20
Tuesday, 2024-05-21
Wednesday, 2024-05-22
Thursday, 2024-05-23
Friday, 2024-05-24
Saturday, 2024-05-25
Sunday, 2024-05-26
dmi@dmi-laptop:~/my_python$ 
```

Wishing everyone joyous days ahead in their calendars, I thank my readers for their attention. May each day be filled with happiness, prosperity, and meaningful moments. Your support and engagement are deeply appreciated, and I look forward to sharing more insights and knowledge.