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

相关推荐
冰冰菜的扣jio2 小时前
理解类加载过程
开发语言·python
百***07452 小时前
GPT-5.2国内稳定接入实战指南:中转调用全链路方案(Python适配)
python·gpt·php
zyxqyy&∞3 小时前
python代码小练-4
开发语言·python
luoluoal3 小时前
基于python的反爬虫技术的研究(源码+文档)
开发语言·python·mysql
老歌老听老掉牙3 小时前
圆柱立铣刀容屑槽几何要素仿真及计算分析
python·立铣刀·容屑槽
hugh_oo3 小时前
100 天学会爬虫 · Day 11:如何合理控制爬虫请求频率?让访问行为更像真人
开发语言·爬虫·python
长安牧笛3 小时前
房贷提前还款测算程序,输入贷款总额,利率,还款年限,计算提前还款后的利息节省金额和月供变化。
python
嘻哈baby3 小时前
Python开发Telegram Bot实现服务器监控告警
python
UtopianCoding3 小时前
什么是NoteDiscovery?Obsidian 的开源平替?
python·docker·开源