Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare multiple dates in a list in Python?

I am wondering how am I able to compare dates in a list. I would like to extract the "earliest" date. (I did a for loop as I had to replace some characters with '-')

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)

Output:

['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']

I want to extract the earliest date:

Eg.

'2018-04-01'

like image 823
glhe13 Avatar asked Jan 01 '26 07:01

glhe13


2 Answers

Just use the min function:

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))

produces

2018-04-01
like image 95
Siong Thye Goh Avatar answered Jan 02 '26 20:01

Siong Thye Goh


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)  
    D.append(date_object)

print(min(D))

You should keep the dates as datetime objects and then use the min() builtin function to determine the earliest date

like image 36
Alexandru Martin Avatar answered Jan 02 '26 20:01

Alexandru Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!