按年,月或日过滤日期列表

时间:2019-11-07 10:46:41

标签: python list date filter

如何按特定的年,月或日过滤datetime.date对象的列表?

示例:

import datetime as dt

dates = [dt.date(2017, 5, 6), dt.date(2015, 5, 13), dt.date(2012, 12, 6), dt.date(2017, 12, 6)]

1 个答案:

答案 0 :(得分:0)

import datetime as dt

dates = [dt.date(2017, 5, 6), dt.date(2015, 5, 13), dt.date(2012, 12, 6), dt.date(2017, 12, 6)]

# Filter by year
dates_2017 = list(filter(lambda x: x.year == 2017, dates))

# Filter by month
dates_may = list(filter(lambda x: x.month == 5, dates))

# Filter by day
dates_6th = list(filter(lambda x: x.day == 6, dates))