You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Pandas生成无年份的全年日期范围(1/1至31/12)

如何用Pandas生成无年份的全年日期范围(1/1 至 31/12)

给你两种实用的实现方式,按需选择:

方法一:基于闰年日期范围提取月日

先利用闰年(比如2020年)生成完整的全年日期序列,这样能自动包含2月29日,之后再提取月日部分即可:

import pandas as pd

# 生成2020年(闰年)的完整日期范围
full_date_range = pd.date_range(start='2020-01-01', end='2020-12-31')

# 方式1:转为无年份的字符串列表(格式如"01/01")
no_year_date_strings = full_date_range.strftime('%m/%d')

# 方式2:保留datetime类型,统一将年份设为0(或任意固定值)
no_year_datetime = full_date_range.map(lambda dt: dt.replace(year=0))

如果不需要包含2月29日,把起始年份换成平年(比如2023)就行。

方法二:手动遍历月份构建日期

通过循环每个月份,结合日历模块获取每月天数,手动生成所有月日组合:

import pandas as pd
from calendar import monthrange

no_year_dates = []
# 遍历1-12月
for month in range(1, 13):
    # 用闰年2020计算当月天数,确保包含2月29
    _, days_count = monthrange(2020, month)
    # 遍历当月所有天数,格式化月日字符串
    for day in range(1, days_count + 1):
        no_year_dates.append(f"{month:02d}/{day:02d}")

# 转为Pandas Series方便后续处理
no_year_series = pd.Series(no_year_dates)

# 也可以转为datetime对象(年份设为0)
no_year_datetime_series = pd.to_datetime(no_year_dates, format='%m/%d').replace(year=0)

内容的提问来源于stack exchange,提问作者Abdulrahman Itman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 04:45:42