简体   繁体   English

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

[英]How to convert int64 to datetime in pandas

I have a pandas dataframe that has a column of type int64 but this columns represets date, eg 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?我该如何修复我的代码?

You need a capital Y .你需要一个大写的Y See Python's strftime directives for a complete reference.有关完整参考,请参阅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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM