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
相关产品推荐
相关产品推荐

