以下是一个代码示例,用于比较日期并找到匹配的年份和月份。
from datetime import datetime
def find_matching_date(date_list, year, month):
matching_dates = []
for date_str in date_list:
date = datetime.strptime(date_str, "%Y-%m-%d")
if date.year == year and date.month == month:
matching_dates.append(date)
return matching_dates
# Example usage
dates = [
"2021-01-10",
"2021-02-15",
"2021-03-20",
"2022-01-05",
"2022-02-10"
]
matching_dates = find_matching_date(dates, 2021, 2)
for date in matching_dates:
print(date.strftime("%Y-%m-%d"))
在上面的代码中,我们定义了一个find_matching_date
函数,它接受一个日期列表、年份和月份作为参数。函数遍历日期列表中的每个日期,并使用datetime.strptime
函数将字符串转换为日期对象。然后,我们比较日期对象的年份和月份是否与传入的参数匹配。如果匹配,我们将日期对象添加到matching_dates
列表中。
在示例用法中,我们使用提供的日期列表和参数调用find_matching_date
函数,然后遍历匹配的日期对象并将其格式化为字符串后打印出来。这样,我们就可以找到匹配的年份和月份的日期。