Search code examples
pythondatedifferencepython-datetime

Difference between two dates (datetime)


I'm trying to write a program in Python that calculates the number of days between two dates.

I'm getting input from the user in the format May 2 2020. I have learned that I should first parse a string to a date, but I don't know how to do that. Please help me.

Here is the program I have tried:

from datetime import date

first_date(input)
sec_date(input)
con_date = datetime.strptime(first_date, '%d %m %Y').date()
con_date2 = datetime.strptime(first_date, '%d %m %Y').date()
delta = con_date2 - con_date
print(delta)

If I give input in the form of string May 2 2020 for the first_date and Jun 30 2020 for the sec_date, how can I convert this string into date format? Note: input should be given in the above format only.

The above code is not working for me to convert a string to a date. Please help me convert it into date and find the number of days between sec_date to first_date.


Solution

  • You can simply parse the time using the appropriate strptime format.

    Then, once you’ve obtained two date objects, you can simply subtract them:

    import datetime 
    
    d1_str = "Apr 29 2020"
    d2_str = "May 7 2020"
    
    fmt = "%b %d %Y"
    
    d1 = datetime.datetime.strptime(d1_str, fmt).date()
    d2 = datetime.datetime.strptime(d2_str, fmt).date()
    
    delta = d2 - d1
    print(delta)
    print(delta.days)
    

    Output is:

    6 days, 0:00:00
    6