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

Python如何基于timestamp按月份对时间戳列表进行分组

时间戳按月份分组实现方案(Python)

核心逻辑是将Unix时间戳转换为datetime对象,提取月份数值后按月份归类存储,以下是可直接运行的实现代码:

from datetime import datetime

def group_timestamps_by_month(timestamps):
    group_result = {}
    for ts in timestamps:
        # 按本地时区转换,如需UTC时区可替换为datetime.utcfromtimestamp(ts)
        current_dt = datetime.fromtimestamp(ts)
        month = current_dt.month
        if month not in group_result:
            group_result[month] = []
        group_result[month].append(ts)
    return group_result

# 测试示例
ts_list = [1231469744, 1231470173, 1231470988, 1231471428, 1545730073]
print(group_timestamps_by_month(ts_list))
# 输出符合预期:{1: [1231469744, 1231470173, 1231470988, 1231471428], 12: [1545730073]}

注意事项

  • 默认适配秒级Unix时间戳,如果输入的是毫秒级时间戳,需要先除以1000转成秒级再传入函数
  • 时区可根据需求调整,UTC时区下替换转换方法即可,避免跨时区场景下月份计算偏差

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 07:27:03