K.I.S.S---Keep IT Simple,Stupid!    人生苦短,我用Python

python to print all the days of a year by months in calandar format and generate a picture to show all the dates .

 
分类: 问答 2024年3月13日

Certainly! Let’s create a single image that displays the entire 2024 calendar. We’ll use Python and the Pillow (PIL) library to generate the image.

Here are two methods to achieve this:

  1. Using the calendar Module: We can utilize the built-in calendar module to generate the calendar for each month in 2024. Then, we’ll arrange these monthly calendars into a single image. Here’s an example using the calendar module:

    Python

     

    import calendar
    from PIL import Image, ImageDraw, ImageFont
    
    def generate_calendar_image(year):
        # Create a blank image
        image_width, image_height = 800, 600
        img = Image.new("RGB", (image_width, image_height), color="white")
        draw = ImageDraw.Draw(img)
        font = ImageFont.load_default()
    
        # Set initial position for drawing
        x, y = 20, 20
    
        # Generate and draw each month's calendar
        for month in range(1, 13):
            cal = calendar.month(year, month)
            draw.text((x, y), f"{calendar.month_name[month]} {year}", fill="black", font=font)
            draw.text((x, y + 30), cal, fill="black", font=font)
            x += 200  # Move to the next column
    
        # Save the image
        img.save("2024_calendar.png")
        print("Calendar image saved as 2024_calendar.png")
    
    generate_calendar_image(2024)
    

    AI-generated code. Review and use carefully. More info on FAQ.

    This script will create an image named 2024_calendar.png with all the months arranged in columns.

  2. Custom Calendar Generation: If you prefer a more customized layout, we can create our own grid of dates for each month. Here’s an example:

    Python

     

    import calendar
    from datetime import date
    from PIL import Image, ImageDraw, ImageFont
    
    def generate_custom_calendar_image(year):
        # Create a blank image
        img_width, img_height = 800, 600
        img = Image.new("RGB", (img_width, img_height), color="white")
        draw = ImageDraw.Draw(img)
        font = ImageFont.load_default()
    
        # Set initial position for drawing
        x, y = 20, 20
    
        # Generate and draw each month's custom calendar
        for month in range(1, 13):
            first_day = date(year, month, 1).weekday()
            num_days = calendar.monthrange(year, month)[1]
    
            # Initialize the calendar grid
            cal = [[" " for _ in range(7)] for _ in range(6)]
    
            # Fill in the days of the month
            day = 1
            for i in range(6):
                for j in range(7):
                    if i == 0 and j < first_day:
                        continue
                    if day > num_days:
                        break
                    cal[i][j] = str(day)
                    day += 1
    
            # Draw the custom calendar
            draw.text((x, y), f"{calendar.month_name[month]} {year}", fill="black", font=font)
            for week in cal:
                draw.text((x, y + 30), " ".join([f"{d:2}" if d != " " else "  " for d in week]), fill="black", font=font)
                y += 20
    
            x += 200  # Move to the next column
    
        # Save the image
        img.save("2024_custom_calendar.png")
        print("Custom calendar image saved as 2024_custom_calendar.png")
    
    generate_custom_calendar_image(2024)
    

    AI-generated code. Review and use carefully. More info on FAQ.

    This script will create an image named 2024_custom_calendar.png with a personalized layout for each month.

Feel free to choose the method that best suits your needs, and adjust the image dimensions, fonts, and other details as desired

import calendar
import datetime
import matplotlib.pyplot as plt
import numpy as np

def get_all_days(year):
    all_days = []
    for month in range(1, 13):
        num_days = calendar.monthrange(year, month)[1]
        for day in range(1, num_days + 1):
            all_days.append(datetime.date(year, month, day))
    return all_days

def plot_calendar(year, holidays, specific_dates):
    all_days_in_year = get_all_days(year)
    fig, ax = plt.subplots(figsize=(12, 8))

    # Plot calendar
    ax.imshow(np.zeros((31, 12)), cmap='gray', aspect='auto')

    # Highlight China holidays (circles)
    for holiday in holidays:
        day, month = holiday.split('-')
        ax.plot(int(month) - 1, int(day) - 1, 'ro', markersize=10)

    # Highlight specific dates (green color)
    for date in specific_dates:
        day, month = date.split('-')
        ax.plot(int(month) - 1, int(day) - 1, 'go', markersize=10)

    # Customize ticks and labels
    ax.set_xticks(np.arange(12))
    ax.set_yticks(np.arange(31))
    ax.set_xticklabels(calendar.month_abbr[1:])
    ax.set_yticklabels(range(1, 32))
    ax.set_title(f"Calendar for {year}")

    plt.show()

# Example usage
year_to_generate = 2024
china_holidays = ["4-4", "5-1", "6-10"]  # Example China holidays
specific_dates = ["1-1", "7-1"]  # Example specific dates

plot_calendar(year_to_generate, china_holidays, specific_dates)
 




注:当前文章会不定期进行更新。如果您对本文有更好的建议,有新资料推荐, 可以点击: 欢迎分享优秀网站
这个位置将来会放广告

我想等网站访问量多了,在这个位置放个广告。网站纯公益,但是用爱发电服务器也要钱啊 ----------狂奔的小蜗牛