Pandas:计算来自不同时区的两个日期时间列之间的差异

Pandas: Calculate the difference between two Datetime columns from different timezones

我有两个不同的时间序列。一个是来自 CET 时区的一系列 ms 格式的时间戳,以字符串形式提供。另一个是 UTC 时区的 s 格式的 unix 时间戳。

它们中的每一个都在一个更大的数据框中的一列中,none 它们是一个 DatetimeIndex,不应该是一个。

我需要将 CET 时间转换为 UTC,然后计算两列之间的差异,我迷失在 Python 和 Pandas 的日期时间功能以及各种不同的数据类型之间.

这是一个例子:

import pandas as pd
import pytz

germany = pytz.timezone('Europe/Berlin')

D1 = ["2016-08-22 00:23:58.254","2016-08-22 00:23:58.254",
      "2016-08-22 00:23:58.254","2016-08-22 00:40:33.260",
      "2016-08-22 00:40:33.260","2016-08-22 00:40:33.260"]

D2 = [1470031195, 1470031195, 1470031195, 1471772027, 1471765890, 1471765890]

S1 = pd.to_datetime(pd.Series(D1))
S2 = pd.to_datetime(pd.Series(D2),unit='s')

第一个问题

tz_localize配合使用。我需要程序理解 S1 中的数据不是 UTC,而是 CET。但是,像这样使用 tz_localize 似乎将给定的日期时间解释为 CET,假设它是 UTC 开头:

F1 = S1.apply(lambda x: x.tz_localize(germany)).to_frame()

尝试 tz_convert 总是抛出类似的东西:

TypeError: index is not a valid DatetimeIndex or PeriodIndex

第二题

即使它们都具有相同的格式,我也卡住了,因为我现在无法计算两列之间的差异:

F1 = S1.apply(lambda x: x.tz_localize(germany)).to_frame()
F1.columns = ["CET"]
F2 = S2.apply(lambda x: x.tz_localize('UTC')).to_frame()
F2.columns = ["UTC"]
FF = pd.merge(F1,F2,left_index=True,right_index=True)
FF.CET-FF.UTC

ValueError: Incompatbile tz's on datetime subtraction ops

我需要一种方法来使用不是 DatetimeIndex 对象的 tz 感知日期时间对象进行这些计算。

或者我需要一种方法让我的 CET 列看起来像这样:

2016-08-21 22:23:58.254
2016-08-21 22:23:58.254
2016-08-21 22:23:58.254
2016-08-21 22:40:33.260
2016-08-21 22:40:33.260
2016-08-21 22:40:33.260

也就是说,我不需要我的日期时间是 tz 感知的,我只是想通过 adding/subtracting 必要的时间自动转换它,并注意夏令时。

如果不是夏令时,我可以对两个整数做一个简单的减法。

首先您需要将 CET 时间戳转换为日期时间并指定时区:

S1 = pd.to_datetime(pd.Series(D1))
T1_cet = pd.DatetimeIndex(S1).tz_localize('Europe/Berlin')

然后将 UTC 时间戳转换为日期时间并指定时区以避免混淆:

S2 = pd.to_datetime(pd.Series(D2), unit='s')
T2_utc = pd.DatetimeIndex(S1).tz_localize('UTC')

现在将 CET 时间戳转换为 UTC:

T1_utc = T1_cet.tz_convert('UTC')

最后计算时间戳的差值:

diff = pd.Series(T1_utc) - pd.Series(T2_utc)