python - Pandas 在阅读 csv 时无法识别日期

标签 python pandas string csv datetime

我正在编写一个脚本,该脚本使用 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/

相关文章:

python - 忽略 pandas DataFrame 中的行

c++ - 为什么 puts in my_strcpy 函数没有打印下面给定代码中的值?

c - 在 Unix 上用 C 读取文本文件的一行——我的 read_line 坏了?

python - 计算打开和关闭时间内的时间方差

python - 带 FTP 的虚拟文件系统

python - 在Shapely中查找多边形上最近点的坐标

python - Python Elasticsearch范围查询

python - 在pandas python中删除文本中的 '\n'

c# - 提供 4 位长的序列号失败

javascript - 无法加载资源:net::ERR_NAME_NOT_RESOLVED