比较列表值并每天选择最大值-Python

时间:2020-06-01 22:36:58

标签: python python-3.x

我正在使用Python 3.6。我有一个下面的列表(通过json对象捕获开始时间),并且想捕获列表中每一天的最新日期/时间值。

mytimelist =[2020-05-30T19:21:36.124Z, 2020-05-31T10:34:06.137Z, 2020-05-31T17:14:06.117Z,2020-05-31T23:06:21.131Z, 2020-06-01T19:21:36.108Z, 2020-06-01T21:55:11.137Z]

我想要以下列表。

myfinallist = [2020-05-30T19:21:36.124Z, 2020-05-31T23:06:21.131Z, 2020-06-01T21:55:11.137Z]

有人可以在这里帮助我吗?

2 个答案:

答案 0 :(得分:1)

解决方案可能包含来自itertools的groupby

from itertools import groupby

mytimelist =['2020-05-30T19:21:36.124Z', '2020-05-31T10:34:06.137Z', '2020-05-31T17:14:06.117Z','2020-05-31T23:06:21.131Z', '2020-06-01T19:21:36.108Z', '2020-06-01T21:55:11.137Z']

for k, v in groupby(sorted(mytimelist), key=lambda x: x[:10]):
    print(list(v)[-1])

2020-05-30T19:21:36.124Z
2020-05-31T23:06:21.131Z
2020-06-01T21:55:11.137Z

更新:按照下面a'r的注释对日期时间条目进行了排序。

答案 1 :(得分:0)

我假设您可以在Python中以字符串形式获取日期?然后,您可以使用datetime将它们转换为datetime个对象,并遍历唯一的日期,并随便检查最大值。

import datetime as dt

mytimelist =['2020-05-30T19:21:36.124Z',
             '2020-05-31T10:34:06.137Z',
             '2020-05-31T17:14:06.117Z',
             '2020-05-31T23:06:21.131Z',
             '2020-06-01T19:21:36.108Z',
             '2020-06-01T21:55:11.137Z']

#see https://strftime.org/ for the syntax
date_format = "%Y-%m-%dT%H:%M:%S.%fZ"
datetimes = [dt.datetime.strptime(t,date_format) for t in mytimelist]

output = {}
for time in datetimes:
    date = time.date()
    if date not in output:
        output[date] = time
    else:
        if time > output[date]:
            output[date] = time

for key in sorted(output.keys()):
    print(str(key) + ': ' + str(output[key]))

输出:

2020-05-30: 2020-05-30 19:21:36.124000
2020-05-31: 2020-05-31 23:06:21.131000
2020-06-01: 2020-06-01 21:55:11.137000
相关问题