如何基于Pandas带时区Timestamp生成对应整数时间戳?
优雅处理Pandas时区偏移量计算问题
现有包含毫秒级UNIX时间戳的数据集:
data = [ { "unix_ts": 1669291200000, "val": 10 }, { "unix_ts": 1669291260000, "val": 25 } ]
将其转换为带US/Eastern时区的Pandas DataFrame:
import pandas as pd df = pd.DataFrame(data) df['ET'] = pd.to_datetime(df['unix_ts'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('US/Eastern')
生成的结果如下:
unix_ts val ET 0 1669291200000 10 2022-11-24 07:00:00-05:00 1 1669291260000 25 2022-11-24 07:01:00-05:00
现在需要生成新列adjusted_ts,要求根据每行ET字段对应的实际时区偏移量(夏令时为-4小时,冬令时为-5小时)对原unix_ts做调整。之前用字符串切片提取偏移量的方法虽然可行,但不够优雅,这里用Pandas原生方法实现适配夏令时的计算。
优雅实现方案
直接利用Pandas Timestamp的dt.utcoffset()方法获取每行的时区偏移时长,转换为毫秒后参与计算:
# 计算时区偏移的毫秒数,再调整原时间戳 df['adjusted_ts'] = df['unix_ts'] + (df['ET'].dt.utcoffset().dt.total_seconds() * 1000).astype(int)
逻辑说明
dt.utcoffset()会返回当前时区时间与UTC的时差,比如US/Eastern冬令时返回-1 days +19:00:00(等价于-5小时),夏令时返回-1 days +20:00:00(等价于-4小时)total_seconds()将时差转换为总秒数,乘以1000得到毫秒级偏移量- 原
unix_ts是UTC时间的毫秒数,加上偏移量后,就得到了适配当地时区偏移的调整后时间戳,和之前字符串切片的计算结果完全一致,且能自动适配夏令时/冬令时的变化
比如测试夏令时场景:
# 夏令时示例:2023-06-01 UTC 12:00,对应US/Eastern 08:00-04:00 test_data = [{"unix_ts": 1685611200000, "val": 30}] test_df = pd.DataFrame(test_data) test_df['ET'] = pd.to_datetime(test_df['unix_ts'], unit='ms').dt.tz_localize('UTC').dt.tz_convert('US/Eastern') test_df['adjusted_ts'] = test_df['unix_ts'] + (test_df['ET'].dt.utcoffset().dt.total_seconds() * 1000).astype(int)
此时adjusted_ts会自动用-4小时的偏移计算,无需手动修改逻辑。
内容的提问来源于stack exchange,提问作者HapiDaze
相关产品推荐
相关产品推荐

