计算时间戳之间的差异并存储在字典中



>我有一本名为 times 的字典,其中包含一个日期时间时间戳作为键,元组作为值。示例格式如下:

{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:

我该怎么做?提前感谢任何帮助。

以下内容应该有效

# 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)

最新更新