简体   繁体   English

python列表中的最大日期

[英]max date in python list

I have an list: 我有一个清单:

a=[datetime.date(2010,10,20),1,4,datetime.date(2013,10,20)]

As you can see the list contains different types of elements. 如您所见,列表包含不同类型的元素。 How can I get the max date within the list? 如何获得列表中的最大日期?

My attempt: 我的尝试:

from datetime import datetime
b=datetime.max(a)
print b

First, keeping dates and integers together in the same list -- except as an intermediate step -- can be a sign your data structure isn't appropriate. 首先,将日期和整数保存在同一个列表中 - 除了作为中间步骤 - 可能是您的数据结构不合适的标志。 That said, you can easily take the max only of the dates by using a generator expression: 也就是说,您可以使用生成器表达式轻松地仅使用日期的最大值:

>>> import datetime
>>> a=[datetime.date(2010,10,20),1,4,datetime.date(2013,10,20)]
>>> max(d for d in a if isinstance(d, datetime.date))
datetime.date(2013, 10, 20)

For guidence Find oldest/youngest datetime object in a list 用于指导在列表中查找最旧/最年轻的日期时间对象

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(2015, 2, 12, 10, 10), # future
    datetime(2016, 2, 12, 10, 10), # future
]
oldest = min(datetime_list)
youngest = max(datetime_list)

The prior post has filter to exclude future events 之前的帖子有过滤器以排除未来事件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM