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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3922644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 13:21:43  来源:igfitidea点击:

Find oldest/youngest datetime object in a list

pythondatetimecompare

提问by panosl

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() 与其中的每一个进行比较。

采纳答案by eumiro

Oldest:

最老的:

oldest = min(datetimes)

Youngest before now:

以前最年轻:

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

回答by Gabi Purcaru

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

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

回答by JoshD

Given a list of dates dates:

给定日期列表dates

Max date is max(dates)

最大日期是 max(dates)

Min date is min(dates)

最小日期是 min(dates)

回答by jknair

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)

回答by Malik A. Rumi

The datetime module has its own versions of min and max as available methods. https://docs.python.org/2/library/datetime.html

datetime 模块有自己的 min 和 max 版本作为可用方法。https://docs.python.org/2/library/datetime.html