【Python】创建日期列表

1. 问题:给出年份和月份,返回该月日期列表

2. AI方案(DeepSeek)

对话词:

python给出年份和月份,返回该月的日期字符串列表,日期字符串格式是20251103,列表是'20251101',...,'20251130'

方法1:直接实现(推荐)

python

复制代码
from datetime import date, timedelta

def get_month_date_strings(year, month):
    """
    返回指定年份和月份的日期字符串列表
    格式:'YYYYMMDD',如 '20251101', '20251102', ..., '20251130'
    """
    # 获取该月的第一天
    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)
    
    # 生成日期字符串列表
    date_strings = []
    current_day = first_day
    while current_day <= last_day:
        # 格式化为YYYYMMDD
        date_str = current_day.strftime("%Y%m%d")
        date_strings.append(date_str)
        current_day += timedelta(days=1)
    
    return date_strings

# 使用示例
if __name__ == "__main__":
    # 测试2025年11月
    dates = get_month_date_strings(2025, 11)
    print(f"2025年11月的日期字符串列表:")
    print(dates)
    print(f"\n列表长度(天数):{len(dates)}")
    print(f"第一天:{dates[0]}")
    print(f"最后一天:{dates[-1]}")

方法2:简洁版(列表推导式)

python

复制代码
from datetime import date, timedelta

def get_month_date_strings_simple(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)
    
    # 计算天数差
    num_days = (last_day - first_day).days + 1
    
    # 使用列表推导式生成日期字符串
    return [(first_day + timedelta(days=i)).strftime("%Y%m%d") 
            for i in range(num_days)]

# 使用示例
dates = get_month_date_strings_simple(2025, 11)
print(f"2025年11月的所有日期:")
# 每行显示5个日期
for i in range(0, len(dates), 5):
    print(dates[i:i+5])

方法3:使用calendar模块

python

复制代码
import calendar
from datetime import date

def get_month_date_strings_calendar(year, month):
    """使用calendar模块的实现"""
    # 获取该月的天数
    _, num_days = calendar.monthrange(year, month)
    
    # 生成日期字符串列表
    date_strings = []
    for day in range(1, num_days + 1):
        d = date(year, month, day)
        date_strings.append(d.strftime("%Y%m%d"))
    
    return date_strings

# 使用示例
dates = get_month_date_strings_calendar(2025, 11)
print(f"2025年11月日期列表:")
print(dates)

3. 根据AI改写

本来很简单的功能,感觉AI写的啰嗦了。

python 复制代码
def get_month_date_strings_calendar(year, month):
    """使用calendar模块的实现"""
    # 获取该月的天数
    _, num_days = calendar.monthrange(year, month)
    
    # 生成日期字符串列表
    date_strings = [f'{year}{month:02d}{day:02d}' for day in range(1, num_days+1)]
    
    return date_strings

# 使用示例
dates = get_month_date_strings_calendar(2025, 11)
print(f"2025年11月日期列表:")
print(dates)

这里,首先使用calendar模块获取该月的天数,然后用天数这个整数变量,采用字符串拼接的方式,构造出日期列表。这个方法减少 date 类型的使用,更快更简洁。

相关推荐
代码山河3 小时前
Python就业方向全解析:后端、爬虫、数据分析、AI你选哪个?
python·学习·架构·教程·面向对象·项目
在世修行3 小时前
智学文枢:题目流水线
python·多线程·状态机·pyside
梯度下降者4 小时前
零基础入门Python 爬虫
爬虫·python·数据分析·入门指南·webcrawler
“AI国潮设计-小江”5 小时前
【AIGC实战】Python+Stable Diffusion打造“英歌舞财神”IP,解锁“马到成功”等爆款情绪营销文案设计
开发语言·人工智能·python·prompt·aigc
benchmark_cc6 小时前
用 Python 拉 A 股全市场实时快照:Notebook 请求、结果校验与易错点
python·数据分析·pandas·量化交易·股票数据·quantdash
伞伞悦读6 小时前
【第70期】Adam二阶矩不是方差:偏差校正、动量与AdamW完整实验
python
外收内放7 小时前
Python基础语法练习题(73)
java·前端·python
锋行天下7 小时前
Langgraph HITL 中断运行,用户输入后输出打字效果
人工智能·python
时早玖沐7 小时前
给 AstrBot 写一个天气推送插件:12 次提交、6 个坑
python·开源·ai编程
触底反弹7 小时前
🚀 FastAPI 五大重难点深度剖析:从 500 报错到彻底搞懂 Depends、Pydantic 与 SQLAlchemy
python·fastapi