我正在编写一个脚本,该脚本使用 pandas 读取 .csv 文件并填写特定表格。 .csv 文件中的一列是生日列。
在读取 .csv 文件时,我使用“parse_dates”对其进行解析以获取日期时间对象,以便根据需要对其进行格式化:
df = pd.read_csv('readfile1.csv',sep=';', parse_dates=['birthday'])
虽然它与 readfile1.csv 完美配合,但不适用于 readfile2.csv。但是这些文件看起来完全一样。
我得到的错误让我认为通过 pandas 自动解析到日期时间是行不通的:
print(df.at[i,'birthday'].strftime("%d%m%Y"))
AttributeError: 'str' object has no attribute 'strftime'
在这两种情况下,生日的格式如下:
'1965-05-16T12:00:00.000Z' #from readfile1.csv
'1934-04-06T11:00:00.000Z' #from readfile2.csv
我不知道哪里出了问题。我检查了文件的编码,都是“UTF-8”。有什么想法吗?
谢谢! 问候
最佳答案
if you do not set keyword parse_dates, and convert the column after reading the csv, with pd.to_datetime and keyword errors='coerce', what result do you get? does the column have NaT values? – MrFuppes 32 mins ago
MrFuppes 关于调用 pd.to_datetime 的评论导致成功。列中的一个错误日期是错误的原因。 Lumber Jacks 的提示也有助于确定数据类型!
关于python - Pandas 在阅读 csv 时无法识别日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66061028/