You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Pandas中处理含夏令时(DST)变更的15分钟间隔本地时间数据

解决Pandas处理CE(S)T夏令时重复时间戳的自动推断问题

针对CE(S)T时区夏令时切换(2024-10-27 02:00前后)出现的重复15分钟间隔时间戳,无需手动调整行顺序的处理方法如下:

  1. 标准化时间列:先将原始时间字符串转换为不带时区的datetime类型:

    df['timestamp'] = pd.to_datetime(df['timestamp'])
    
  2. 自动排序时间序列:利用Pandas内置排序对时间列进行升序排列,确保时间序列连续有序:

    df = df.sort_values('timestamp').reset_index(drop=True)
    
  3. 本地化时区并推断歧义时间:使用tz_localize指定目标时区,同时通过ambiguous='infer'让Pandas根据序列连续性自动识别重复时间对应的时区(首次为夏令时UTC+2,第二次为冬令时UTC+1):

    df['timestamp'] = df['timestamp'].dt.tz_localize('Europe/Amsterdam', ambiguous='infer')
    

完整示例代码

import pandas as pd

# 模拟包含乱序重复时间戳的数据集
data = {
    'timestamp': [
        '2024-10-27 01:45:00',
        '2024-10-27 02:30:00',
        '2024-10-27 02:00:00',
        '2024-10-27 02:15:00',
        '2024-10-27 02:45:00',
        '2024-10-27 02:00:00',
        '2024-10-27 02:15:00',
        '2024-10-27 02:30:00',
        '2024-10-27 02:45:00',
        '2024-10-27 03:00:00'
    ],
    'value': range(10)
}

df = pd.DataFrame(data)

# 自动处理流程
df['timestamp'] = pd.to_datetime(df['timestamp'])
df = df.sort_values('timestamp').reset_index(drop=True)
df['timestamp'] = df['timestamp'].dt.tz_localize('Europe/Amsterdam', ambiguous='infer')

# 验证结果
print(df['timestamp'])

这种方法无需硬编码排序规则,仅通过Pandas原生操作即可让ambiguous='infer'正常工作,避免手动调整行顺序的繁琐操作。

内容的提问来源于stack exchange,提问作者Python404

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 11:48:22