Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

greater than 'date' python 3

I would like to be able to do greater than and less than against dates. How would I go about doing that? For example:

date1 = "20/06/2013"
date2 = "25/06/2013"
date3 = "01/07/2013"
date4 = "07/07/2013"


datelist = [date1, date2, date3]

for j in datelist:
     if j <= date4:
          print j

If I run the above, I get date3 back and not date1 or date2. I think I need I need to get the system to realise it's a date and I don't know how to do that. Can someone lend a hand?

Thanks

like image 487
Simkill Avatar asked Jul 22 '26 07:07

Simkill


2 Answers

You can use the datetime module to convert them all to datetime objects. You are comparing strings in your example:

>>> from datetime import datetime
>>> date1 = datetime.strptime(date1, "%d/%m/%Y")
>>> date2 = datetime.strptime(date2, "%d/%m/%Y")
>>> date3 = datetime.strptime(date3, "%d/%m/%Y")
>>> date4 = datetime.strptime(date4, "%d/%m/%Y")
>>> datelist = [date1, date2, date3]
>>> for j in datelist:
...      if j <= date4:
...           print(j.strftime('%d/%m/%Y'))
... 
20/06/2013
25/06/2013
01/07/2013
like image 101
TerryA Avatar answered Jul 24 '26 00:07

TerryA


You are comparing strings, not dates. You should use a date-based object-type, such as datetime.

How to compare two dates?

like image 20
Erwin Avatar answered Jul 24 '26 01:07

Erwin



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!