非常感谢您的帮助。
我正在尝试将 ISO 格式的字符串日期时间转换为日期时间对象。但是尝试了很多方法都没有成功。请您对此提供帮助。
例如,我有一个列时间类似于如下所示的数据框。这是从数据库中提取的,这是输出的格式。
2018-12-04T04:39:26Z
2018-12-04T05:10:54.6Z
2018-12-04T05:17:32Z
2018-12-04T10:51:20.5Z
...
到目前为止我已经尝试过(多次尝试)但没有成功:
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'))
再次感谢!
最佳答案
之前就想回答这个问题。最后,我只是做了一个处理不同数据输入的函数,还创建了一个带有列名的数据框。感谢 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')
转换为日期时间后,检查日期是否正确。如果读取错误,您可能需要指定格式。
谢谢!
关于python - 来自特定 ISO 格式的 Pandas 日期时间转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53657769/