【问题标题】:python pandas datetime datetime does not work wellpython pandas datetime datetime 不能正常工作
【发布时间】:2017-10-15 12:24:33
【问题描述】:

我尝试了很多方法来解决这个问题,但都没有奏效。

我想将pandas 系列转换为datetime

我想我可能错过了一些小而重要的部分。

print test["order_date"][3]
print type(test["order_date"][3])

test["order_date"] = pd.to_datetime(test["order_date"], format="%Y-%m-%d %H:%M:%S")

##have also tried 
##test["order_date"] = pd.to_datetime(test["order_date"], infer_datetime_format=True) 
##test["order_date"] = test["order_date"].apply(pd.to_datetime)
##all turn out to be the same result

print test["order_date"][3]
print type(test["order_date"][3])

结果如下:

20150731000001
<type 'numpy.int64'>

1970-01-01 05:35:50.731000001 
<class 'pandas.tslib.Timestamp'>

我不明白为什么result 变成1970-01-01

如果需要任何进一步的信息,请告诉我。

谢谢!

【问题讨论】:

  • 格式错误,因此数字 20150731000001 自 1970 年以来被解释为 ms - 这与您的结果相对应。

标签: python pandas datetime


【解决方案1】:

您指定了错误的格式。

试试这个:

In [34]: pd.to_datetime(['20150731000001'], format="%Y%m%d%H%M%S")
Out[34]: DatetimeIndex(['2015-07-31 00:00:01'], dtype='datetime64[ns]', freq=None)

【讨论】:

  • @LeighTsai,很高兴它有帮助:)
【解决方案2】:

因为dtype是int64所以它假设纳秒单位值:

In[51]:
pd.to_datetime(20150731000001, unit='ns')
Out[51]: Timestamp('1970-01-01 05:35:50.731000001')

如果它是一个字符串,那么它将能够正确解析:

In[54]:
pd.to_datetime('20150731000001')
Out[53]: Timestamp('2015-07-31 00:00:01')

因此,您可以显式传递格式字符串(如 @MaxU 的答案)或将列的 dtype 转换为 str,然后传递:

test["order_date"] = pd.to_datetime(test["order_date"].astype(str))

【讨论】:

    猜你喜欢
    • 2022-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    相关资源
    最近更新 更多