【问题标题】:How to use Python get same date hour or minute from datetime list?如何使用 Python 从日期时间列表中获取相同的日期小时或分钟?
【发布时间】:2020-05-14 15:10:52
【问题描述】:

我有一个时间列表,我需要获取列表中具有相同小时、分钟或秒的所有元素,并将它们组成新列表。

示例: 列表

['10:20:01', '10:20:02', '10:21:00', '10:21:01', '10:22:00', '10:22:01']

出来

['10:20:01', '10:20:02']
['10:21:00', '10:21:01']
['10:22:00', '10:22:01']

【问题讨论】:

标签: python algorithm datetime


【解决方案1】:
from datetime import datetime
from collections import defaultdict
q = ['10:20:01', '10:20:02', '10:21:00', '10:21:01', '10:22:00', '10:22:01']
t = []
for i in q:    
    w = (datetime.strptime(i,"%H:%M:%S").time()) # Converting str to time
    t.append((w.hour,w.minute)) # Storing only hours and minutes
buckets = defaultdict(list)
for tup in t:
    buckets[tup].append(tup) # Check time and append to coressponding dict key(Hour,minute)
buckets = list(buckets.values())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-03
    • 1970-01-01
    • 2015-11-04
    相关资源
    最近更新 更多