You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python求助:用循环与条件语句生成当月日期星期列表

Python实现当月日期与对应星期的列表输出

下面是满足需求的代码,用循环和条件语句实现,注释清晰,适合新手理解:

import datetime

# 获取当前月份的第一天
current_date = datetime.date.today().replace(day=1)
# 记录当前月份,用于判断循环终止条件
current_month = current_date.month

# 定义星期对应的中文名称,对应weekday()返回的0-6索引(0=周一,6=周日)
weekday_names = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]

print("当月日期与星期列表:")
print("------------------------")
# 循环遍历当月所有日期
while current_date.month == current_month:
    # 获取当前日期的星期索引
    weekday_index = current_date.weekday()
    # 匹配对应的中文星期名称
    weekday_name = weekday_names[weekday_index]
    # 格式化输出,让日期数字占2位,保持列表整齐
    print(f"{current_date.day:2d}号 - {weekday_name}")
    # 将日期加1天,进入下一次循环
    current_date += datetime.timedelta(days=1)

关键步骤说明

  • 依赖Python标准库datetime,Linux系统默认Python环境已自带,无需额外安装。
  • replace(day=1)快速获取当月第一天,避免手动计算当月天数的麻烦。
  • while循环通过判断日期的月份是否等于当前月份,自动终止循环(无需手动指定当月天数)。
  • 用列表映射星期索引到中文名称,比一堆if-elif条件判断更简洁易维护。
  • f"{current_date.day:2d}"让1-9号的日期显示为两位数字宽度(前面补空格),输出的列表更整齐。

扩展:指定月份输出

如果需要输出某个特定月份的日期,只需修改current_date的初始化代码,比如输出2024年6月的日期:

current_date = datetime.date(2024, 6, 1)
current_month = current_date.month

内容的提问来源于stack exchange,提问作者Rebecca E

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 14:08:19