Search code examples
pythondatetimetimedelta

Find time difference between two dates in python


I am trying to find the time difference between the two given dates in the following format: YYYY-MM-DD HH-MM-SS

I have checked the examples, but they use datetime.datetime etc, no specific format of date and time.


Solution

  • import datetime
    
    dt_str_a = '2020-06-29 16:15:27'
    dt_str_b = '2020-07-12 12:00:00'
    
    
    dt_a = datetime.datetime.strptime(dt_str_a, '%Y-%m-%d %H:%M:%S')
    dt_b = datetime.datetime.strptime(dt_str_b, '%Y-%m-%d %H:%M:%S')
    
    print(dt_b - dt_a)
    print((dt_b - dt_a).days)
    

    ->

    12 days, 19:44:33    # <---- precise value
    12                   # <---- number of days only