'Looking for days between two given dates in a string format
I do have data like this: [a, startdate, enddate]
a_list = [ ['a', '2021-02-22', '2021-02-25'] ]
and would like to get the days between those two dates to be like [a, startdate, enddate, days between those dates]
a_list = [ ['a', '2021-02-22', '2021-02-25', 3] ]
How do I approach this problem? Thanks in advance!
Solution 1:[1]
Working out of the box solution:
from datetime import datetime
a_list = [ ['a', '2021-02-22', '2021-02-25'] ]
res = []
for el in a_list:
d1 = datetime.strptime(el[1], '%Y-%M-%d')
d2 = datetime.strptime(el[2], '%Y-%M-%d')
res.append(el + [(d2-d1).days])
res
>>> [['a', '2021-02-22', '2021-02-25', 3]]
Solution 2:[2]
Turn your strings into
datetime.datetypesimport datetime a_dt = datetime.date.strptime(a_list[0][1],'%Y-%m-%d') b_dt = datetime.date.strptime(a_list[0][2],'%Y-%m-%d')Compute the
datetime.timedeltadifference between themdays_between = (b_dt - a_dt).days # Assuming b_dt is after a_dt for +ve daysAppend the result to your list.
a_list[0].append( days_between )
Solution 3:[3]
This is the easiest way to reach your goal.
from datetime import datetime
a_list = [ ['a', '2021-02-22', '2021-02-25'] ]
start_date = datetime.strptime(a_list[0][1], '%Y-%M-%d')
end_date = datetime.strptime(a_list[0][2], '%Y-%M-%d')
days = (end_date-start_date).days
a_list[0].append(days)
print(a_list)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | politinsa |
| Solution 2 | Wondercricket |
| Solution 3 | Nayem Jaman Tusher |
