我有一个名为times的字典,其中包含一个datetime时间戳作为键,而元组作为值。格式示例如下:
{datetime.datetime(2019, 11, 4, 20, 2): ('A', 'B'),
datetime.datetime(2019, 11, 4, 19, 59): ('C', 'D'),
datetime.datetime(2019, 11, 4, 19, 55): ('E', 'F'), …, }
我正在尝试按升序对列表中的时间戳进行排序,循环遍历列表以计算连续时间戳之间的差异,如果差异大于10分钟阈值,则将开始时间存储在新字典中(并以相应的元组作为值)。
到目前为止,这是我要编写的代码。我相信我需要先在列表time_with_breaks中存储时间戳之间的差异,然后使用大于字典中阈值的if语句存储增量,但我不确定如何执行此操作。
deltas = {} # store timestamp and seconds until next entry
time_with_breaks = [] # store timing information of breaks
# sorted list of time stamps (ascending order)
timelist = sorted(playlist_dict.keys(), reverse=False)
for i in timelist:
我该怎么做?在此先感谢您的帮助。
答案 0 :(得分:0)
以下应该可以工作
# This will return an ordered list of the timestamps
times_sorted = list(sorted(playlist_dict.keys()))
time_with_breaks = []
# "zipping" the list with itself offset by 1 will give you an iterable
# of each timestamp and the next timestamp in the list
for time_1, time_2 in zip(times_sorted, times_sorted[1:]):
# datetime - datetime results in a timedelta
# 600 seconds is 10 minutes
if (time_2 - time_1).seconds > 600:
# Append the datetime where the next datetime in the list is more than
# 10 minutes away
time_with_breaks.append(time_1)