Python 下的万年历小程序,包括农历

实现万年历小程序(含农历)

Python 可以通过 lunarcalendardatetime 库实现万年历功能,农历转换依赖第三方库 lunarcalendar。以下为完整实现方案:


安装依赖库

确保安装 lunarcalendardatetime(后者为 Python 内置库):

pip install lunarcalendar


核心代码实现

from lunarcalendar import Lunar, Solar, Converter
from datetime import datetime

def print_calendar(year, month):
    # 打印公历和农历
    print(f"\n公历 {year}年{month}月")
    print("日 一 二 三 四 五 六")

    first_day = datetime(year, month, 1)
    weekday = first_day.weekday()  # 0-6 对应周一至周日
    print("   " * weekday, end="")

    for day in range(1, 32):
        try:
            current_date = datetime(year, month, day)
            solar = Solar(current_date.year, current_date.month, current_date.day)
            lunar = Converter.Solar2Lunar(solar)
            
            # 对齐输出
            print(f"{day:2}", end=" ")
            if current_date.weekday() == 6:  # 周六换行
                print()
        except:
            break  # 超出当月天数

    # 显示农历信息(示例:当月第一天农历)
    lunar_date = Converter.Solar2Lunar(Solar(year, month, 1))
    print(f"\n农历 {lunar_date.year}年{lunar_date.month}月{lunar_date.day}日")

# 示例调用
print_calendar(2023, 10)


功能扩展

  1. 节假日标记
    添加字典标记节假日,例如:

    holidays = {
        (1, 1): "元旦",
        (5, 1): "劳动节",
        (10, 1): "国庆节"
    }
    

  2. 用户交互
    通过 input 让用户输入年份和月份:

    year = int(input("输入年份:"))
    month = int(input("输入月份:"))
    print_calendar(year, month)
    


输出示例

运行 print_calendar(2023, 10) 会显示:

公历 2023年10月
日 一 二 三 四 五 六
 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
农历 2023年八月十七日


注意事项

  1. lunarcalendar 库的农历日期转换范围为 1900-2100 年。
  2. 如需更复杂的界面,可结合 tkinterPyQt 实现 GUI。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

std86021

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值