在列表中查找最旧/最年轻的日期时间对象

时间:2022-05-31 22:50:56

I've got a list of datetime objects, and I want to find the oldest or youngest one. Some of these dates might be in the future.

我有一个日期时间对象列表,我想找到最老或最年轻的对象。其中一些日期可能在将来。

from datetime import datetime

datetime_list = [
    datetime(2009, 10, 12, 10, 10),
    datetime(2010, 10, 12, 10, 10),
    datetime(2010, 10, 12, 10, 10),
    datetime(2011, 10, 12, 10, 10), #future
    datetime(2012, 10, 12, 10, 10), #future
]

What's the most optimal way to do so? I was thinking of comparing datetime.now() to each one of those.

什么是最佳方式?我在考虑将datetime.now()与其中的每一个进行比较。

4 个解决方案

#1


86  

Oldest:

最老的:

oldest = min(datetimes)

Youngest before now:

现在最小的:

now = datetime.datetime.now(pytz.utc)
youngest = max(dt for dt in datetimes if dt < now)

#2


20  

Given a list of dates dates:

给出日期列表日期:

Max date is max(dates)

最大日期是最大(日期)

Min date is min(dates)

最短日期是分钟(日期)

#3


11  

Datetimes are comparable; so you can use max(datetimes_list) and min(datetimes_list)

日期时间可比;所以你可以使用max(datetimes_list)和min(datetimes_list)

#4


4  

have u tried this :

你试过这个:

>>> from datetime import datetime as DT
>>> l =[]
>>> l.append(DT(1988,12,12))
>>> l.append(DT(1979,12,12))
>>> l.append(DT(1979,12,11))
>>> l.append(DT(2011,12,11))
>>> l.append(DT(2022,12,11))
>>> min(l)
datetime.datetime(1979, 12, 11, 0, 0)
>>> max(l)
datetime.datetime(2022, 12, 11, 0, 0)

#1


86  

Oldest:

最老的:

oldest = min(datetimes)

Youngest before now:

现在最小的:

now = datetime.datetime.now(pytz.utc)
youngest = max(dt for dt in datetimes if dt < now)

#2


20  

Given a list of dates dates:

给出日期列表日期:

Max date is max(dates)

最大日期是最大(日期)

Min date is min(dates)

最短日期是分钟(日期)

#3


11  

Datetimes are comparable; so you can use max(datetimes_list) and min(datetimes_list)

日期时间可比;所以你可以使用max(datetimes_list)和min(datetimes_list)

#4


4  

have u tried this :

你试过这个:

>>> from datetime import datetime as DT
>>> l =[]
>>> l.append(DT(1988,12,12))
>>> l.append(DT(1979,12,12))
>>> l.append(DT(1979,12,11))
>>> l.append(DT(2011,12,11))
>>> l.append(DT(2022,12,11))
>>> min(l)
datetime.datetime(1979, 12, 11, 0, 0)
>>> max(l)
datetime.datetime(2022, 12, 11, 0, 0)