Find time difference between two dates in python

Question:

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.

Asked By: Arseniy Sleptsov

||

Answers:

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
Answered By: Gab
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.