我正在将数据导入 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
这建立在 FObersteiner 之前的回答之上。
如果列的类型为datetime64[ns]
,请使用
Series.dt.tz
:
col.dt.tz is None
如果列的类型为 object
或
pd.Timestamp
,则不支持
.dt
,因此请使用
Timestamp.tz
代替:
col.apply(lambda t: t.tz is None).all()
tz
属性:
这里有一个简单的检查方法:
import pandas as pd
# Example Timestamp
timestamp = pd.Timestamp('2024-01-01 12:00:00')
# Check if the Timestamp is timezone aware
if timestamp.tz is not None:
print("The timestamp is timezone aware.")
else:
print("The timestamp is timezone naive.")