How do I get the difference between two dates in years, months, and days?
There are two dates:
date1 = 20201231
date2 = 20311105
How to get the difference between them in the form:
d_years = date2-date1
d_months = date2-date1
d_days = date2-date1
print(f'delta : \n in days {d_days}\n in months {d_months}\n in years {d_years}')
3
1 answers
Use the convenient module dateutil:
from dateutil.parser import parse as du_parse
from dateutil.relativedelta import relativedelta
d1 = du_parse(str(date1))
d2 = du_parse(str(date2))
delta = relativedelta(d2, d1)
In [14]: delta.years
Out[14]: 10
In [15]: delta.months
Out[15]: 10
In [16]: delta.days
Out[16]: 5
Total number of months:
In [76]: delta.years * 12 + delta.months
Out[76]: 130
The exact total number of days - to do this, just use the attribute .days
from the date difference:
In [78]: (d2 - d1).days
Out[78]: 3961
Examples of using the parser:
In [68]: du_parse('20200509')
Out[68]: datetime.datetime(2020, 5, 9, 0, 0)
In [69]: du_parse('2020-05-09')
Out[69]: datetime.datetime(2020, 5, 9, 0, 0)
In [70]: du_parse('2020/05/09 11:12:13')
Out[70]: datetime.datetime(2020, 5, 9, 11, 12, 13)
In [71]: du_parse('Tuesday 5 May 2020')
Out[71]: datetime.datetime(2020, 5, 5, 0, 0)
By default, if the first number is 09.05.2020 we get 5 сентября 2020
:
In [72]: du_parse('09.05.2020')
Out[72]: datetime.datetime(2020, 9, 5, 0, 0)
You can explicitly specify that the first number is days:
In [74]: du_parse('09.05.2020', dayfirst=True)
Out[74]: datetime.datetime(2020, 5, 9, 0, 0)
3
Author: MaxU, 2020-05-17 07:36:44