Reputation: 487
Can you tell me why this compaison code doesn't work?
DateStart= '16/07/2020'
DateEnd = '24/10/2020'
for i in range(14,124):
date_depart = date.today()+timedelta(days=i)
date_retour = date.today()+timedelta(days=(i+row['duree_sejour']))
if (date_depart.strftime('%d/%m/%Y') >=datetime.strptime(DateStart, '%d/%m/%Y').strftime('%d/%m/%Y')) \
and (date_retour.strftime('%d/%m/%Y') >=datetime.strptime(DateEnd, '%d/%m/%Y').strftime('%d/%m/%Y')):
print("Depearture: {}. Back: {}.".format(date_depart.strftime('%d/%m/%Y'),date_retour.strftime('%d/%m/%Y')))
It returns this output:
Depearture: 18/07/2020. Back: 25/07/2020. Depearture: 19/07/2020. Back: 26/07/2020. Depearture: 20/07/2020. Back: 27/07/2020. Depearture: 21/07/2020. Back: 28/07/2020. Depearture: 22/07/2020. Back: 29/07/2020. Depearture: 23/07/2020. Back: 30/07/2020. Depearture: 24/07/2020. Back: 31/07/2020. Depearture: 18/08/2020. Back: 25/08/2020. Depearture: 19/08/2020. Back: 26/08/2020. Depearture: 20/08/2020. Back: 27/08/2020. Depearture: 21/08/2020. Back: 28/08/2020. Depearture: 22/08/2020. Back: 29/08/2020. Depearture: 23/08/2020. Back: 30/08/2020. Depearture: 24/08/2020. Back: 31/08/2020. Depearture: 18/09/2020. Back: 25/09/2020. Depearture: 19/09/2020. Back: 26/09/2020. Depearture: 20/09/2020. Back: 27/09/2020. Depearture: 21/09/2020. Back: 28/09/2020. Depearture: 22/09/2020. Back: 29/09/2020. Depearture: 23/09/2020. Back: 30/09/2020. Depearture: 17/10/2020. Back: 24/10/2020. Depearture: 18/10/2020. Back: 25/10/2020. Depearture: 19/10/2020. Back: 26/10/2020. Depearture: 20/10/2020. Back: 27/10/2020. Depearture: 21/10/2020. Back: 28/10/2020. Depearture: 22/10/2020. Back: 29/10/2020. Depearture: 23/10/2020. Back: 30/10/2020. Depearture: 24/10/2020. Back: 31/10/2020.
Why do we pass directly from '24/07/2020' date to '18/08/2020'? Thanks a lot. Théo
Upvotes: 0
Views: 26
Reputation: 350
You are doing a rich comparison between str
objects, which does not contain the appropriate logic for the chronological comparison of dates. Instead, you can do:
from datetime import date, datetime, timedelta
date_start = date(2020, 7, 16)
date_end = date(2020, 10, 24)
for i in range(14, 124):
date_depart = (datetime.today()+timedelta(days=i)).date()
date_retour = (datetime.today()+timedelta(days=(i+row['duree_sejour']))).date()
if (date_depart >= date_start) and (date_retour <= date_end):
print("Depearture: {}. Back: {}.".format(date_depart, date_retour))
Here, we build datetime.Date
objects, for which there is an explicit meaning to <
, >
, <=
>=
etc - it understands the chronology of dates.
Upvotes: 1