本文介绍了在列表中查找最旧/最年轻的日期时间对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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.
解决方案
Oldest:
oldest = min(datetimes)
Youngest before now:
now = datetime.datetime.now(pytz.utc)
youngest = max(dt for dt in datetimes if dt < now)
这篇关于在列表中查找最旧/最年轻的日期时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!