首页 > 解决方案 > 如何比较 Python 列表中的多个日期?

问题描述

我想知道如何比较列表中的日期。我想提取“最早”的日期。(我做了一个for循环,因为我必须用'-'替换一些字符)

comment_list = comment_container.findAll("div", {"class" : "comment-date"})
D =[]

  for commentDate in comment_list:
    year, month, day = map(int, commentDate.split('-'))
    date_object = datetime(year, month, day)
    date_object = datetime.strptime(commentDate, '%Y-%m-%d').strftime('%Y-%m-%d')   
    D.append(date_object)

print(D)

输出:

['2018-06-26', '2018-04-01', '2018-07-19', '2018-04-23', '2018-08-25', '2018-06-08', '2018-06-14', '2018-07-08', '2019-03-15', '2019-03-15', '2019-03-15', '2019-03-15', '2019-03-15']

我想提取最早的日期:

例如。

'2018-04-01'

标签: pythonlistweb-scrapingbeautifulsoup

解决方案


只需使用 min 函数:

A = ['2018-06-26', '2018-04-01', '2018-07-19', '2018-04-23', '2018-08-25', '2018-06-08', '2018-06-14', '2018-07-08', '2019-03-15', '2019-03-15', '2019-03-15', '2019-03-15', '2019-03-15']
print(min(A))

生产

2018-04-01

推荐阅读