Home > Back-end >  Looking for days between two given dates in a string format
Looking for days between two given dates in a string format

Time:05-18

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!

CodePudding user response:

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]]

CodePudding user response:

  1. Turn your strings into datetime.date types

    import 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')
    
  2. Compute the datetime.timedelta difference between them

    days_between = (b_dt - a_dt).days # Assuming b_dt is after a_dt for  ve days
    
  3. Append the result to your list.

    a_list[0].append( days_between )
    

CodePudding user response:

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)

CodePudding user response:

If you have two date objects, you can just subtract them, which computes a timedelta object.

from datetime import date

d0 = date(2008, 8, 18)
d1 = date(2008, 9, 26)
delta = d1 - d0
print(delta.days)
  • Related