Home > OS >  Check if date is between two dates without year included
Check if date is between two dates without year included

Time:07-20

I have a datetime date in the format yyyy-mm-dd and I want to check if the date entered falls between for example May 15th and May 25th without including any year value.

tripDate_str = str(input("Please enter the trip start date in the following format: YYYY-MM-DD "))

import datetime
tripDate = datetime.datetime.strptime(tripDate_str, "%Y-%m-%d")

CodePudding user response:

Well I guess the simplest approach is to use the month and day date class attributes

import datetime
tripDate = datetime.datetime.strptime('2022-05-15', "%Y-%m-%d")

start = datetime.datetime.strptime('2022-05-10', "%Y-%m-%d")
end = datetime.datetime.strptime('2022-05-20', "%Y-%m-%d")

if tripDate.month >= start.month and tripDate.month <= end.month and tripDate.day >= start.day and tripDate.day <= end.day:
    print('Date in range')
else:
    print('Date not in range')

CodePudding user response:

There are many options to get the day of the year from a date. Use a search engine with keywords python day of year to find out which. The code below is using for this purpose strftime('%j'):

tripDate_str = str(input("Please enter the trip start date in the following format: YYYY-MM-DD "))
# tripDate_str = "2022-05-18"
## Finding day of year
from datetime import date
tripDate_dayOfYear = date(*map(int, tripDate_str.split('-'))).strftime('%j')
print("tripDate_dayOfYear: ", tripDate_dayOfYear)

tripDate_year = date(*map(int, tripDate_str.split('-'))).strftime('%Y')
dateRangeBeg_dayOfYear = date(int(tripDate_year), 5, 15).strftime('%j')
dateRangeEnd_dayOfYear = date(int(tripDate_year), 5, 25).strftime('%j')
if dateRangeBeg_dayOfYear <= tripDate_dayOfYear <= dateRangeEnd_dayOfYear:
    print("tripDate falls into range", dateRangeBeg_dayOfYear, dateRangeEnd_dayOfYear)
else:
    print("tripDate is outside range", dateRangeBeg_dayOfYear, dateRangeEnd_dayOfYear)

To avoid a problem with switch years tripDate_year is used in setting the values of dateRangeBeg_dayOfYear and dateRangeEnd_dayOfYear.

  • Related