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

处理Pandas DataFrame:为缺失年份的时间戳添加2020年

为缺失年份的时间序列添加2020年并转换为datetime格式

针对你提供的缺失年份的时间数据,这里有两种实用方法来完成需求:

方法一:字符串拼接后直接转换

先给每个时间字符串前缀加上2020/,再用pd.to_datetime指定格式完成转换:

import pandas as pd

# 假设数据存储在df的DateTime列中
df['DateTime'] = '2020/' + df['DateTime']
# 按指定格式转换为datetime类型
df['DateTime'] = pd.to_datetime(df['DateTime'], format='%Y/%m/%d  %H:%M:%S')

如果需要保持输出为你期望的字符串格式(而非datetime对象),可以追加格式化步骤:

df['DateTime'] = df['DateTime'].dt.strftime('%Y/%m/%d  %H:%M:%S')

方法二:先解析时间再替换年份

先解析无年份的时间字符串,再统一替换年份为2020:

import pandas as pd

# 先解析时间(此时默认年份会取当前系统年份)
df['DateTime'] = pd.to_datetime(df['DateTime'], format='%m/%d  %H:%M:%S')
# 将所有时间的年份替换为2020
df['DateTime'] = df['DateTime'].dt.replace(year=2020)

注意:原数据中的12/31 24:00:00转换为datetime对象时,会自动转为2021-01-01 00:00:00,这是datetime类型的标准逻辑(不存在24:00的时间点)。如果需要保持显示为2020/12/31 24:00:00,请使用方法一中的字符串格式化步骤。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:51:06