【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 类型的使用,更快更简洁。

相关推荐
love530love9 小时前
LiveTalking 数字人项目 Windows 部署完全指南(EPGF 架构)
人工智能·windows·python·架构·livetalking·epgf
遇事不決洛必達9 小时前
【Python基础】GIL 锁是什么及其对爬虫的影响
爬虫·python·线程·进程·gil锁
CryptoPP10 小时前
快速对接东京证券交易所API数据:实战指南与代码示例
开发语言·人工智能·windows·python·信息可视化·区块链
探物 AI10 小时前
把 MambaOut 塞进 YOLOv11:会有什么样的反应
python·yolo·计算机视觉
如竟没有火炬11 小时前
最大矩阵——单调栈
数据结构·python·线性代数·算法·leetcode·矩阵
阳区欠11 小时前
【LangChain】LLM基础介绍
开发语言·python·langchain
Cosolar11 小时前
保姆级 CrewAI 教程:从零构建多智能体协作系统
人工智能·python·架构
GDAL11 小时前
使用 uv 管理 Python 版本
python·uv·版本
真实的菜11 小时前
Redis 从入门到精通(十二):典型业务场景实战 —— 排行榜、限流器、秒杀系统、Session 共享
数据库·redis·python
cup1112 小时前
[开源] Meta Assistant / 告别命令行,我为一堆 Python 脚本做了一个 Windows 任务栏的“家”
windows·python·工具·nuitka·脚本运行