【问题标题】:How to work with a Dataframe with a column/series of dtype object and having different +z values如何使用具有一列/一系列 dtype 对象并具有不同 +z 值的数据框
【发布时间】:2021-08-21 02:59:17
【问题描述】:

您好,我有一个数据框,其中一个名为“格式化日期”的列包含2006-04-01 00:00:00.000 +0200 之类的对象。我正在尝试将其转换为日期时间,并且我使用了

format='%Y-%m-%d %H:%M:%S.%f %z'  

它不起作用,因为 +z 值并非对所有人都相同。如何首先使时区相同?

df['Formatted Date']=pd.to_datetime(df['Formatted Date'], format='%Y-%m-%d %H:%M:%S.%f %z')

【问题讨论】:

  • 该格式看起来正确。您确定所有行都有正确格式的值吗?
  • 请分享确切的错误消息和一些导致您未预料到的错误的示例数据。
  • @sharon 请edit 这个问题而不是使用 cmets。注释故意不支持代码块。
  • 我在下面找到了我的答案。感谢回复:stackoverflow.com/questions/55385497/…

标签: python pandas datetime datetime-format


【解决方案1】:

使用关键字utc=True 解析为日期时间。如果您不知道数据的原始时区,我建议您在此处继续使用 UTC。但是,如果你知道时区,你可以tz_convert 给它,例如

import pandas as pd

df = pd.DataFrame({'Formatted Date': ["2006-02-01 00:00:00.000 +0100", 
                                      "2006-04-01 00:00:00.000 +0200"]})
df['Formatted Date'] = pd.to_datetime(df['Formatted Date'], utc=True)

# df['Formatted Date']
# 0   2006-01-31 23:00:00+00:00
# 1   2006-03-31 22:00:00+00:00
# Name: Formatted Date, dtype: datetime64[ns, UTC]

df['Formatted Date'] = df['Formatted Date'].dt.tz_convert('Europe/Berlin')

df['Formatted Date'] 
0   2006-02-01 00:00:00+01:00
1   2006-04-01 00:00:00+02:00
Name: Formatted Date, dtype: datetime64[ns, Europe/Berlin]

【讨论】:

  • 非常感谢您的回答。真的很有帮助。
  • @sharonchetia 我没有注意到您已经找到了解决方案,正如您在 cmets 部分中提到的那样。我建议将问题作为副本关闭;但你不妨把它留在这里,让其他人也能找到其他问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多