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

如何正确设置自定义时间?Pandas Timestamp使用异常求助

解决pd.Timestamp传入自定义日期得到1970年日期的问题

问题根源

你写的1/12/2020在Python中是除法运算,计算结果约为0.00004115,pd.Timestamp()会把这个数值当作Unix时间戳(从1970-01-01 00:00:00开始的秒数),所以得到的是起始日期附近的时间。

正确实现方式

根据你想要的目标日期(比如2020年12月1日或2020年1月12日),可以用以下几种方法:

1. 传入日期字符串

直接传入带格式的字符串,注意日期顺序:

  • 如果是月/日/年(1月12日):
import pandas as pd
x = pd.Timestamp("1/12/2020")
print(x)
# 输出: 2020-01-12 00:00:00
  • 如果是日/月/年(12月1日),需要指定dayfirst=True:
x = pd.Timestamp("1/12/2020", dayfirst=True)
print(x)
# 输出: 2020-12-01 00:00:00

2. 传入年、月、日参数

更明确的方式,直接指定年月日:

x = pd.Timestamp(year=2020, month=12, day=1)  # 对应2020-12-01
# 或者 x = pd.Timestamp(year=2020, month=1, day=12) 对应2020-01-12
print(x)

3. 用pd.to_datetime处理(可选)

如果需要批量转换或处理格式,也可以用pd.to_datetime:

x = pd.to_datetime("1/12/2020", dayfirst=True)
print(x)

额外说明

你原来代码中的pd.to_datetime(x, unit="s")是多余的,因为x已经是Timestamp类型,再次转换不会改变结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 13:08:32