【问题标题】:Check if datetime object in pandas has a timezone?检查 pandas 中的 datetime 对象是否有时区?
【发布时间】:2020-10-26 02:47:17
【问题描述】:

我正在将数据导入 pandas 并希望删除任何时区 - 如果它们存在于数据中。如果数据有时区,下面的代码就成功了:

col = "my_date_column"
df[col] = pd.to_datetime(df[col]).dt.tz_localize(None) # We don't want timezones...

如果数据不包含时区,我想使用以下代码:

df[col] = pd.to_datetime(df[col])

我的问题是我不确定如何在日期时间对象/系列中测试时区。

【问题讨论】:

  • 如果没有时区,您可以将.dt.tz_localize(None) 应用于所有列,它不会更改此列。
  • 您确定要本地化为无吗?你也可以转换为无,见here

标签: python pandas datetime timezone


【解决方案1】:

假设您有一个日期时间类型的列,您可以检查该列中每个时间戳的tzinfo。它基本上被描述为here(尽管这不是特定于pytz)。例如:

import pandas as pd

# example series:
s = pd.Series([
        pd.Timestamp("2020-06-06").tz_localize("Europe/Berlin"), # tzinfo defined
        pd.Timestamp("2020-06-07") # tzinfo is None
        ])

# s
# 0    2020-06-06 00:00:00+02:00
# 1          2020-06-07 00:00:00
# dtype: object
  
# now find a mask which is True where the timestamp has a timezone:
has_tz = s.apply(lambda t: t.tzinfo is not None)

# has_tz
# 0     True
# 1    False
# dtype: bool

【讨论】:

    【解决方案2】:

    这建立在prior answer by MrFuppes 之上。

    如果列的类型为datetime64[ns],则使用Series.dt.tz:

    col.dt.tz is None
    

    如果列是pd.Timestamp 的object 类型,则不支持.dt,因此请改用Timestamp.tz:

    col.apply(lambda t: t.tz is None).all()
    

    【讨论】:

      猜你喜欢
      • 2023-01-26
      • 2013-09-12
      • 2018-01-12
      • 2015-11-10
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 2018-09-10
      相关资源
      最近更新 更多