我正在将数据导入 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 https://stackoverflow.com/questions/5802108/how-to-check-if-a-datetime-object-is-localized-with-pytz(虽然这并不特定于pytz
). Ex:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)