以下是一个示例代码,用于按特定时间戳对日期进行按天分组:
import datetime
# 定义时间戳列表
timestamps = [1567804800, 1567891200, 1567977600, 1568064000, 1568150400, 1568236800]
# 创建一个字典来存储按天分组的日期
date_groups = {}
# 遍历时间戳列表
for timestamp in timestamps:
# 将时间戳转换为日期对象
date = datetime.datetime.fromtimestamp(timestamp).date()
# 检查日期是否已经存在于字典中
if date in date_groups:
# 如果日期已经存在,则将时间戳添加到对应的日期列表中
date_groups[date].append(timestamp)
else:
# 如果日期不存在,则创建一个新的日期列表,并将时间戳添加到其中
date_groups[date] = [timestamp]
# 打印按天分组的结果
for date, timestamps in date_groups.items():
print(f"日期:{date}")
print(f"时间戳:{timestamps}")
print()
输出结果如下:
日期:2019-09-07
时间戳:[1567804800]
日期:2019-09-08
时间戳:[1567891200]
日期:2019-09-09
时间戳:[1567977600]
日期:2019-09-10
时间戳:[1568064000]
日期:2019-09-11
时间戳:[1568150400]
日期:2019-09-12
时间戳:[1568236800]
这个示例代码将给定的时间戳列表按照日期进行分组,并将相同日期的时间戳存储在一个列表中。最后,打印出每个日期以及对应的时间戳列表。