【问题标题】:While performing the time Series Analysis I have got the error Date time while converting the string to datetime在执行时间序列分析时,将字符串转换为日期时间时出现错误日期时间
【发布时间】:2020-10-18 12:56:31
【问题描述】:

我有日期列中的数据,我想转换为日期时间,出现如下错误

    Month   Sales of shampoo over a three year period
0   1-01    266.0
1   1-02    145.9
2   1-03    183.1
3   1-04    119.3
4   1-05    180.3

pd.to_datetime(data['Month'])

错误:-

OutOfBoundsDatetime: Out of bounds nanosecond timestamp: 1-01-01 00:00:00

在这种情况下我应该怎么做:-

【问题讨论】:

  • 什么是“月”列格式?它是“月日”吗?
  • 这里1代表年份,02代表当年月份

标签: python pandas datetime time-series


【解决方案1】:

我认为你有一个零填充问题。如果您使用“01”而不是“1”,则可以将对象转换为 DateTime。

就这样;

x=['1-01','1-02','1-03','1-04','1-05']
y=[266.0,145.9,183.1,119.3,180.3]
data=pd.DataFrame(list(zip(x,y)),columns=['month','sth'])
data['month']='0'+data['month']
data['month']=pd.to_datetime(data['month'],format='%y-%m')
data['month']=data['month'].dt.strftime('%y-%m') # to convert 2-digits

【讨论】:

  • OP 的输入似乎是“1-01”,而不是“01-01”。所以你可能想添加data['month'] = '0' + data['month']
【解决方案2】:

我觉得你应该试试:

pd.to_datetime(data['Month'], format="%y-%m")

【讨论】:

  • 这里 1 代表年份,05 和 06 以此类推代表月份
  • 我改变了答案。我想这就是你想要的。
猜你喜欢
  • 2022-01-26
  • 1970-01-01
  • 2015-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-30
  • 2022-08-18
  • 1970-01-01
相关资源
最近更新 更多