从 Datetimeindex Pandas Series 当地时间获取 UTC 偏移量(以小时为单位)

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

我有一个

datetime_index
参数,它是一个已识别时区(UTC 时区)的 Datetimeindex 系列,但我需要获取时区“欧洲/里斯本”的小时偏移值。

我正在使用这个功能:

def get_offset(datetime_index):

    local = pytz.timezone('Europe/Lisbon')
    dt = datetime_index
    offset = [local.utcoffset(dt[x], is_dst=True).seconds / 3600 for x in range(dt.__len__())]
    return offset

但是现在,UTC 格式的值不再有效。

后来我将

offset
变量更改为:

def get_offset(datetime_index):

    local = pytz.timezone('Europe/Lisbon')
    offset = [datetime_index[x].astimezone(local).utcoffset().seconds/3600 for x in range(len(datetime_index))]
    return offset

它似乎有效,但我有点担心在大型数据集中使用它的后果。还有其他办法吗?或者这样也可以吗?

python python-3.x
1个回答
0
投票

如果有人仍然需要它,这里有一种矢量化的方法。与循环相比(如 OP 所示),它快了 100 倍以上。

import pandas as pd
import time

def utcoffset_loop(t):
    offset = [t[i].utcoffset().total_seconds() / 3600 for i in range(len(t))]
    offset = pd.to_timedelta(offset, unit='hour')
    return offset

def utcoffset_vectorized(t):
    t_utc = t.tz_convert('UTC')
    offset = t.tz_localize(None) - t_utc.tz_localize(None)
    return offset

t = pd.date_range(start='2000-01-01', end='2001-01-01', periods=1000000, tz='Europe/Paris')
t1 = time.time()
offset_loop = utcoffset_loop(t)
t2 = time.time()
offset_vectorized = utcoffset_vectorized(t)
t3 = time.time()
print('Loop solution: {}s'.format(t2-t1))
print('Vectorized solution: {}s'.format(t3-t2))

输出:

Loop solution: 8.840850114822388s
Vectorized solution: 0.05070185661315918s
© www.soinside.com 2019 - 2024. All rights reserved.