NPD*_*NPD 4 python string datetime dataframe pandas
如何将“2020-06-30 15:20:13.078196+00:00”形式的日期列转换为 pandas 中的日期时间?
这就是我所做的:
pd.concat([df, df.date_string.apply(lambda s: pd.Series({'date':datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f%z')}))], axis=1)
pd.concat([df, df.file_created.apply(lambda s: pd.Series({'date':datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f.%z')}))], axis=1)
pd.concat([df, df.file_created.apply(lambda s: pd.Series({'date':datetime.strptime(s, '%Y-%m-%dT%H:%M:%S.%f:%z')}))], axis=1)
我收到错误 -time data '2020-06-30 15:20:13.078196+00:00' does not match format
在所有情况下。任何帮助表示赞赏。
+00:00
是 UTC 零小时偏移量,因此可以解释为 UTC。最简单的事情是让pd.to_datetime自动推断格式。这对于像这样的标准格式( ISO 8601 )非常有效:
import pandas as pd
dti = pd.to_datetime(["2020-06-30 15:20:13.078196+00:00"])
print(dti)
# DatetimeIndex(['2020-06-30 15:20:13.078196+00:00'], dtype='datetime64[ns, UTC]', freq=None)
Run Code Online (Sandbox Code Playgroud)
笔记
format="ISO8601"
指定您的输入采用该格式。它甚至允许解析 ISO8601 兼容字符串的混合:example。pd.to_datetime
对于混合格式也非常有效:example。在 pandas v2 中,您可以format="mixed"
在这种情况下进行设置。