简体   繁体   English

使用格式将字符串转换为日期时间

[英]Converting string to datetime with format

I have a column in my dataframe that looks like this, but the current dtype is object. 我的数据框中有一个看起来像这样的列,但是当前的dtype是object。 This dataframe is imported from a csv where there were no column heads and it didn't recognize the type when it imported. 此数据帧是从没有列头的csv导入的,并且在导入时无法识别类型。

time
2019-05-29 12:52:35  
2019-05-29 12:50:41   
2019-05-29 12:51:39  
2019-05-29 12:52:32 
2019-05-29 12:52:18

I've done datetime conversions before but I can't figure the format out. 我之前做过日期时间转换,但无法弄清楚格式。 The documentation and other questions about this don't really help me, to the point I've been trial and erroring but no success. 文档和其他与此有关的问题并没有真正帮到我,我一直在试错,但没有成功。

this is the code i use now: 这是我现在使用的代码:

df['time'] = pd.to_datetime(df.time, format='%Y%m%d %H:%M:%S')

which gives me this error: 这给了我这个错误:

ValueError: time data 0 doesn't match format specified

I've also tried: 我也尝试过:

df['time'] = pd.to_datetime(df.time, format='%Y%m%d%H:%M:%S')

but then I get this error: 但是然后我得到这个错误:

time data '2019-05-29 12:52:35' does not match format '%Y%m%d%H:%M:%S' (match)

I don't understand why I get different errors or what I am doing wrong. 我不明白为什么会遇到其他错误或做错了什么。

您可以尝试两件事:

  1. pd.to_datetime(df['time'], dayfirst=True)
  2. pd.to_datetime(df['time'], format='%Y-%m-%d %H:%M:%S', errors='coerce')

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

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