检查 pandas 中的日期时间对象是否有时区?
Check if datetime object in pandas has a timezone?
我正在将数据导入 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])
我的问题是 我不确定如何在日期时间对象/系列中测试时区。
假设你有一个日期时间类型的列,你可以检查列中每个时间戳的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
这建立在 的基础上。
如果列的类型为 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()
我正在将数据导入 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])
我的问题是 我不确定如何在日期时间对象/系列中测试时区。
假设你有一个日期时间类型的列,你可以检查列中每个时间戳的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
这建立在
如果列的类型为 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()