Pandas —— 时区处理tz_localize()、tz_convert()

rng = pd.date_range('3/9/2012 9:30', periods=6, freq='D')
ts = pd.Series(np.random.randn(len(rng)), index=rng)
ts
2012-03-09 09:30:00    0.070052
2012-03-10 09:30:00    0.721449
2012-03-11 09:30:00   -0.266241
2012-03-12 09:30:00   -1.022387
2012-03-13 09:30:00   -1.476888
2012-03-14 09:30:00    0.770954
Freq: D, dtype: float64

1、时区定位和转换

tz_localize()时区定位

# 定位时区
ts_utc = ts.tz_localize('UTC')
ts_utc
2012-03-09 09:30:00+00:00    0.070052
2012-03-10 09:30:00+00:00    0.721449
2012-03-11 09:30:00+00:00   -0.266241
2012-03-12 09:30:00+00:00   -1.022387
2012-03-13 09:30:00+00:00   -1.476888
2012-03-14 09:30:00+00:00    0.770954
Freq: D, dtype: float64

tz_convert()时区转换

# 转换时区
ts_utc.tz_convert('America/New_York')
2012-03-09 04:30:00-05:00    0.070052
2012-03-10 04:30:00-05:00    0.721449
2012-03-11 05:30:00-04:00   -0.266241
2012-03-12 05:30:00-04:00   -1.022387
2012-03-13 05:30:00-04:00   -1.476888
2012-03-14 05:30:00-04:00    0.770954
Freq: D, dtype: float64

2、UTC时间戳

有时区的Timestamp对象内部存储了一个UTC时间戳,这个值是从Unix纪元(即1907年1月1日)到现在的纳秒;这个UTC值在即使换了不同的时区,也是不变的

ts.index[0]
Timestamp('2012-03-09 09:30:00-0500', tz='America/New_York', freq='D')

ts.index[0].value
1331303400000000000L

3、不同时区间的运算

如果两个不同时区的时间序列被合并,那么结果为UTC。因为时间戳是以UTC为背后机制的,这种变化是直接的,不需要手动转换

ts1 = ts.tz_convert('Europe/London')
ts2 = ts.tz_convert('Europe/Moscow')

result=ts1+ts2
result
2012-03-09 14:30:00+00:00   -2.109895
2012-03-10 14:30:00+00:00   -2.319051
2012-03-11 13:30:00+00:00   -0.750670
2012-03-12 13:30:00+00:00    1.559730
2012-03-13 13:30:00+00:00    0.468756
2012-03-14 13:30:00+00:00   -1.679084
Freq: D, dtype: float64

猜你喜欢

转载自blog.csdn.net/starter_____/article/details/81429817