-1

I have already defined a function to check if a given date is a valid date or not. Now I must find out a) difference between 2 dates b) date 2 should not be less than date 1 c) date 2 and date 1 must be valid dates. I have to incorporate the first function (i.e., valid date function) into the second function.

import datetime

def is_valid_date (year, month, day):
    """
    check if the input date is a valid date or not.
    """
    if month == 1 or month == 3 or month == 5 or month == 7 or month == 8 or month == 10 or month == 12:
        max_days = 31
        
    elif month == 4 or month == 6 or month == 9 or month == 11:
        max_days = 30
    elif year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
        max_days = 29
    else:
        max_days = 28
        
    if (month < 1 or month > 12) or (day < 1 or day > max_days) or (year < 1 or year > 9999):
        return "Invalid Date"
           
    else:
        return "Valid Date"
    
def days_between(year, month, day, year1, month1, day1):
    result = is_valid_date (year, month, day)
    
    if datetime.date (year1, month1, day1) != result:
        return 0
       
    elif datetime.date (year,month,day) != result:
        return 0
      
    elif datetime.date (year1, month1, day1) < datetime.date (year, month, day):
        return 0
        
    else:
        date1= (year, month, day)
        date2= (year1, month1, day1)
        difference = datetime.date (date2) - datetime.date (date1)
        return difference
    
print (is_valid_date(2000, 12,1))
print (days_between(2000,12,1,2000,12,20))

Code is returning the following answers:

Valid Date
0

What I would like to get:

Valid Date
19
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
python
  • 1
  • 2
  • Your first if condition `if datetime.date (year1, month1, day1) != result` is always true... `datetime.date` returns a `date` object while `result` is a string (the return value of `is_valid_date `)... – Tomerikoo Jun 28 '21 at 16:32
  • 1
    Does this answer your question? [How to compare two dates?](https://stackoverflow.com/questions/8142364/how-to-compare-two-dates) – Tomerikoo Jun 28 '21 at 16:33

1 Answers1

0

You'd have to change your second function to something like this, which checks for incorrect conditions as well as subtracts dates if everything is correct

def days_between(year, month, day, year1, month1, day1):
    result1 = is_valid_date (year, month, day)
    result2 = is_valid_date (year1, month1, day1)
    if (result1=="Invalid Date")|(result2=="Invalid Date"):
        return 0
      
    elif datetime.date (year1, month1, day1) < datetime.date (year, month, day):
        return 0
        
    else:
        difference = datetime.date (year1, month1, day1) - datetime.date (year, month, day)
        return difference


print (is_valid_date(2000, 12,1))
print (days_between(2000,12,1,2000,12,20))
>>
Valid Date
19 days, 0:00:00
Harsh Sharma
  • 183
  • 1
  • 10