来自特定 ISO 格式的 Pandas 日期时间转换

J. *_*yes 5 python datetime dataframe pandas

非常感谢您的帮助。

我正在尝试将 ISO 格式的字符串日期时间转换为日期时间对象。但是尝试了很多方法都没有成功。请您对此提供帮助。

例如,我有一个列时间类似于如下所示的数据框。这是从数据库中提取的,这是输出的格式。

2018-12-04T04:39:26Z
2018-12-04T05:10:54.6Z
2018-12-04T05:17:32Z
2018-12-04T10:51:20.5Z
...
Run Code Online (Sandbox Code Playgroud)

到目前为止我已经尝试过(多次尝试)但没有成功:

df.index = pd.to_datetime(df.index, format = "%Y-%m-%dT%H:%M:%SZ", errors='ignore')

df.index = pd.to_datetime(df.index)

df.time = df.time.map(lambda x: pd.to_datetime(dt.datetime.strptime(x, '%Y-%m-%dT%H:%M:%SZ'), format = '%d/%m/%Y %H:%M'))
Run Code Online (Sandbox Code Playgroud)

再次感谢!

J. *_*yes 2

我之前就想回答这个问题。最后,我只是创建了一个函数来处理不同的数据输入,并创建一个带有列名的数据框。感谢 ALollz 对 pd.to_datetime(df.index,errors='coerce') 的评论。

因此,为了从 ISO 格式的字符串转换索引,我建立并遵循以下顺序:

df = pd.DataFrame([[-1.8, '2018-09-14T13:36:00Z']], columns = ['current', 'time'])
df.set_index('time', inplace = True)   # make it your index by using the inplace=True
df.index = pd.to_datetime(df.index, errors='coerce')
Run Code Online (Sandbox Code Playgroud)

转换为日期时间后,检查日期是否正确。如果读取错误,您可能需要指定格式。

谢谢!