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

使用MonthEnd(1)后pandas日期格式异常 如何正确获取月末日期

问题原因

原Month列是整数或字符串类型的YYYYMM格式数值,并非pandas datetime类型,直接和MonthEnd时间偏移量运算时,pandas会将原数值误识别为Unix时间戳(从1970-01-01开始计算的秒数),最终得到异常的拼接式时间结果。

解决方案

恢复为原有YYYYMM格式

直接从异常结果的末尾截取原6位年月数值即可:

df['Month'] = df['Month'].astype(str).str[-6:].astype(int)

如果需要字符串类型可去掉末尾的.astype(int)。

正确转换为当月月末日期

先将原YYYYMM格式的内容转换为pandas datetime类型,再追加MonthEnd偏移量即可:

import pandas as pd
from pandas.tseries.offsets import MonthEnd

# 第一步:将YYYYMM转为当月第一天的datetime格式
df['Month'] = pd.to_datetime(df['Month'], format='%Y%m')
# 第二步:追加时间偏移得到当月月末日期
df['Month'] = df['Month'] + MonthEnd(1)

# 若需要输出为YYYY-MM-DD格式的字符串,可额外执行以下代码
# df['Month'] = df['Month'].dt.strftime('%Y-%m-%d')

运行后即可得到你预期的2021-08-31类标准月末日期格式。

内容的提问来源于stack exchange,提问作者Chilam Cheung

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 19:45:03