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写的啰嗦了。

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

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐