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

相关推荐
njsgcs2 小时前
ue python二次开发启动教程+ 导入fbx到指定文件夹
开发语言·python·unreal engine·ue
io_T_T2 小时前
迭代器 iteration、iter 与 多线程 concurrent 交叉实践(详细)
python
华研前沿标杆游学2 小时前
2026年走进洛阳格力工厂参观游学
python
Carl_奕然2 小时前
【数据挖掘】数据挖掘必会技能之:A/B测试
人工智能·python·数据挖掘·数据分析
AI小怪兽3 小时前
基于YOLOv13的汽车零件分割系统(Python源码+数据集+Pyside6界面)
开发语言·python·yolo·无人机
wszy18093 小时前
新文章标签:让用户一眼发现最新内容
java·python·harmonyos
Eric.Lee20213 小时前
python实现 mp4转gif文件
开发语言·python·手势识别·手势交互·手势建模·xr混合现实
EntyIU3 小时前
python开发中虚拟环境配置
开发语言·python
wszy18093 小时前
顶部标题栏的设计与实现:让用户知道自己在哪
java·python·react native·harmonyos
kaizq3 小时前
AI-MCP-SQLite-SSE本地服务及CherryStudio便捷应用
python·sqlite·llm·sse·mcp·cherry studio·fastmcp