如何在 Pandas 中将 int64 转换为日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51544078/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:50:55  来源:igfitidea点击:

How to convert int64 to datetime in pandas

pythonpandasdatetime

提问by HHH

I have a pandas dataframe that has a column of type int64 but this columns represets date, e.g. 20180501. I'd like to convert this column to datetime and I'm having the following code but it returns an error message

我有一个 Pandas 数据框,它有一列类型为 int64 的列,但此列代表日期,例如 20180501。我想将此列转换为日期时间,并且我有以下代码,但它返回一条错误消息

 df['new_date'] = pd.to_datetime(df['old_date'].astype('str'), format = '%y%m%d')

I'm getting the following error message

我收到以下错误消息

ValueError: unconverted data remains: 0501

How can I fix my code?

我该如何修复我的代码?

回答by jpp

You need a capital Y. See Python's strftime directivesfor a complete reference.

你需要一个资本Y。有关完整参考,请参阅Python 的 strftime 指令

df = pd.DataFrame({'old_date': [20180501, 20181230, 20181001]})

df['new_date'] = pd.to_datetime(df['old_date'].astype(str), format='%Y%m%d')

print(df)

   old_date   new_date
0  20180501 2018-05-01
1  20181230 2018-12-30
2  20181001 2018-10-01

回答by CSQL

It could be that the problem arises due to a format error at some places in the dataframe.

问题可能是由于数据帧中某些地方的格式错误引起的。

You could try setting the parameter errors="coerce" to avoid converting those entries and setting them to NaT.

您可以尝试设置参数 errors="coerce" 以避免转换这些条目并将它们设置为 NaT。

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html