解析文本文件中的时间戳并按5分钟间隔进行计数
我的输入是一个普通的文本文件,里面有6000个时间戳,格式大概是这样的:
2011-06-21 13:17:05,905
2011-06-21 13:17:11,371
2011-06-21 13:17:16,380
2011-06-21 13:17:20,074
2011-06-21 13:17:20,174
2011-06-21 13:17:24,749
2011-06-21 13:17:27,210
2011-06-21 13:17:27,354
2011-06-21 13:17:29,231
2011-06-21 13:17:29,965
2011-06-21 13:17:32,100
2011-06-21 13:17:32,250
2011-06-21 13:17:45,482
2011-06-21 13:17:51,998
2011-06-21 13:18:03,037
2011-06-21 13:18:04,504
2011-06-21 13:18:10,019
2011-06-21 13:18:27,434
2011-06-21 13:18:29,960
2011-06-21 13:18:30,525
...
我的输出应该是一个CSV文件,统计从每个整点开始,每5分钟内有多少行时间戳。
输出示例:
From, To, Count
13:00:00, 13:04:59, 0
13:05:00, 13:09:59, 0
13:10:00, 13:14:59, 19
13:15:00, 13:19:59, 24
...
谢谢!
1 个回答
3
这个内容没有经过测试,你需要自己实现时间转换的功能。你需要去时间模块里找一些可以完成你想要的功能的函数。convert_time_string_to_unix_time 这个函数应该把一个时间字符串转换成自1970年1月1日以来的毫秒数(这就是标准的Unix时间戳)。
它的基本原理是把时间分成五分钟一个的小段,然后遍历所有的时间戳,对于每个时间戳所在的小段,找到的时间戳数量就加1。最后,它会遍历所有找到的小段,把它们再转换回时间戳,并打印出每个小段找到的时间戳数量。
SLOT_LENGTH = 1000 * 60 *5
for line in file:
slot = convert_time_string_to_unix_time(line) / SLOT_LENGTH
bucket[slot] = bucket.get(slot, 0) + 1
for slot in sorted(bucket.keys()):
print(
convert_unix_time_to_time_string(slot * SLOT_LENGTH),
convert_unix_time_to_time_string((slot + 1) * SLOT_LENGTH - 1),
bucket[slot]
)