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

pandas提取Timestamp调用strptime报TypeError问题如何解决

报错原因
  • 你通过df.loc[df.col== i, 'Date']获取的end是Pandas的Series对象,即使只有一条匹配结果,也不是单个时间值
  • strptime()方法的作用是将字符串格式的时间转换为时间类型,而你传入的end本身已经是Timestamp时间类型,类型不匹配导致报错
解决方案

首先要先从Series中提取到单个Timestamp值,再直接进行时间运算即可,无需额外做字符串转时间的操作:

import datetime
import pandas as pd

# 提取单个时间戳,.iloc[0]取匹配到的第一条结果
end = df.loc[df.col == i, 'Date'].iloc[0]

# 减1天得到start,转成指定格式字符串
start = (end - datetime.timedelta(days=1)).strftime('%Y-%m-%d')

# 需求中要给end加1天,写法如下,保留时间类型就去掉.strftime部分
end_plus_1d = (end + datetime.timedelta(days=1)).strftime('%Y-%m-%d')

你也可以用Pandas自带的时间偏移方法实现,更适配Pandas的时间类型:

end = df.loc[df.col == i, 'Date'].iloc[0]
# 加1天
end_plus_1d = (end + pd.DateOffset(days=1)).strftime('%Y-%m-%d')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:24:05