处理日期时间格式的“+00:00”

NPD*_*NPD 4 python string datetime dataframe pandas

如何将“2020-06-30 15:20:13.078196+00:00”形式的日期列转换为 pandas 中的日期时间?

这就是我所做的:

  1. 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)
  2. 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)
  3. 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在所有情况下。任何帮助表示赞赏。

MrF*_*pes 6

+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)

笔记

  • pandas v2 允许您设置format="ISO8601"指定您的输入采用该格式。它甚至允许解析 ISO8601 兼容字符串的混合:example
  • pd.to_datetime对于混合格式也非常有效:example。在 pandas v2 中,您可以format="mixed"在这种情况下进行设置。