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

2024-03-29 09:14:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为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_中,然后使用if语句存储大于字典中阈值的delta,但我不确定如何做到这一点

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:

我该怎么做?提前感谢您的帮助


Tags: ofstore列表datetime字典time格式时间
1条回答
网友
1楼 · 发布于 2024-03-29 09:14:38

以下几点应该有效

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

相关问题 更多 >