检查pandas中的日期时间对象是否有时区?

问题描述 投票:0回答:3

我正在将数据导入 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])

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

python pandas datetime timezone
3个回答
8
投票

假设您有一个日期时间类型的列,您可以检查该列中每个时间戳的

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

5
投票

这建立在 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()
    

0
投票
检查

tz
 属性:

要检查 Pandas 时间戳是否支持时区,您可以检查其 tz 属性。如果 tz 属性为 None,则时间戳是时区朴素的。如果它包含时区对象(如 pytz 时区),则时间戳是时区感知的。

这里有一个简单的检查方法:

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.")
    
© www.soinside.com 2019 - 2024. All rights reserved.