Python日历案例如何获取日历数据

wen python案例 25

本文目录导读:

Python日历案例如何获取日历数据

  1. 使用内置 calendar 模块
  2. 使用第三方库 datetime 生成日历数据
  3. 获取节假日日历(使用第三方库)
  4. 生成日历JSON数据
  5. 获取农历日期

我来介绍几种Python获取日历数据的方法:

使用内置 calendar 模块

获取单月日历

import calendar
# 设置每周第一天为周一(0)或周日(6)
calendar.setfirstweekday(calendar.SUNDAY)  # 设置周日为第一天
# 获取2024年3月的日历
cal = calendar.month(2024, 3)
print(cal)
# 输出:
#      March 2024
# Mo Tu We Th Fr Sa Su
#              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

获取全年日历

# 获取2024年全年日历
cal = calendar.calendar(2024)
print(cal)

获取日历数据列表

import calendar
# 获取某个月的天数
print(calendar.monthrange(2024, 3))  # (4, 31) 返回(当月第一天星期索引, 当月天数)
# 获取某个月每周的日期列表
month_calendar = calendar.monthcalendar(2024, 3)
print(month_calendar)
# 输出: [[0, 0, 0, 0, 1, 2, 3], 
#        [4, 5, 6, 7, 8, 9, 10], ...]
# 0表示不属当前月的日期

使用第三方库 datetime 生成日历数据

from datetime import datetime, date, timedelta
import calendar
def get_month_dates(year, month):
    """获取指定月份的所有日期"""
    # 获取月份的第一天和最后一天
    first_day = date(year, month, 1)
    if month == 12:
        last_day = date(year + 1, 1, 1) - timedelta(days=1)
    else:
        last_day = date(year, month + 1, 1) - timedelta(days=1)
    # 生成所有日期
    dates = []
    current = first_day
    while current <= last_day:
        dates.append({
            'date': current,
            'weekday': current.weekday(),  # 0=周一, 6=周日
            'is_weekend': current.weekday() >= 5
        })
        current += timedelta(days=1)
    return dates
# 使用示例
dates = get_month_dates(2024, 3)
for date_info in dates[:5]:  # 只显示前5天
    print(f"{date_info['date']} - 星期{date_info['weekday']}")

获取节假日日历(使用第三方库)

安装 chinese_calendar

pip install chinese_calendar
from datetime import date
import chinese_calendar as calendar
# 检查某天是否为节假日
d = date(2024, 10, 1)
print(calendar.is_holiday(d))  # True (国庆节)
print(calendar.is_workday(d))  # False
# 获取某段时间内的所有节假日
start_date = date(2024, 1, 1)
end_date = date(2024, 12, 31)
holidays = []
workdays = []
for i in range((end_date - start_date).days + 1):
    current_date = start_date + timedelta(days=i)
    if calendar.is_holiday(current_date):
        holidays.append(current_date)
    else:
        workdays.append(current_date)
print(f"2024年节假日数量: {len(holidays)}")
print(f"2024年工作日数量: {len(workdays)}")

生成日历JSON数据

import calendar
from datetime import datetime, timedelta
def generate_calendar_data(year, month):
    """生成结构化的日历数据"""
    # 获取月份的天数和第一天是星期几
    first_weekday, days_in_month = calendar.monthrange(year, month)
    # 生成日历网格
    calendar_data = []
    week = []
    # 填充第一天之前的空白
    for _ in range(first_weekday):
        week.append(None)
    # 填充日期
    for day in range(1, days_in_month + 1):
        current_date = datetime(year, month, day)
        week.append({
            'day': day,
            'weekday': current_date.weekday(),
            'date_str': current_date.strftime('%Y-%m-%d'),
            'is_today': current_date.date() == datetime.now().date()
        })
        if len(week) == 7:
            calendar_data.append(week)
            week = []
    # 填充最后一周的空白
    if week:
        while len(week) < 7:
            week.append(None)
        calendar_data.append(week)
    return {
        'year': year,
        'month': month,
        'month_name': calendar.month_name[month],
        'days_in_month': days_in_month,
        'weeks': calendar_data
    }
# 使用示例
calendar_json = generate_calendar_data(2024, 3)
print(f"月份: {calendar_json['month_name']} {calendar_json['year']}")
print(f"天数: {calendar_json['days_in_month']}")
for week in calendar_json['weeks']:
    print([d['day'] if d else '' for d in week])

获取农历日期

# 使用 lunardate 库
# pip install lunardate
import lunardate
from datetime import date
# 公历转农历
solar_date = date(2024, 3, 15)
lunar_date = lunardate.LunarDate.fromSolarDate(2024, 3, 15)
print(f"公历: {solar_date}")
print(f"农历: {lunar_date.year}年{lunar_date.month}月{lunar_date.day}日")

这些方法可以根据你的需求选择合适的方案:

  • 简单显示:用内置calendar模块
  • 数据计算:用datetime模块
  • 中国节假日:用chinese_calendar
  • 农历:用lunardate

抱歉,评论功能暂时关闭!