Home > Net >  I have a list of dates and I want to subtract actual date from each of them to know how many day pas
I have a list of dates and I want to subtract actual date from each of them to know how many day pas

Time:02-27

I know I should import datetime to have actual date. But the rest is black magic for me right now.

ex. dates = ['2019-010-11', '2013-05-16', '2011-06-16', '2000-04-22']

actual_date = datetime.datetime.now()

How can I subtract this and as a result have new list with days that passed by from dates to actual_date?

CodePudding user response:

If I'm understanding correctly, you need to find the current date, and then find the number of days between the current date and the dates in your list?

If so, you could try this:

from datetime import datetime, date

dates = ['2019-10-11', '2013-05-16', '2011-06-16', '2000-04-22']

actual_date = date.today()

days = []

for date in dates:
    date_object = datetime.strptime(date, '%Y-%m-%d').date()
    days_difference = (actual_date - date_object).days
    days.append(days_difference)

print(days)

What I am doing here is:

  • Converting the individual date strings to a "date" object
  • Subtracting the this date from the actual date. This gets you the time as well, so to strip that out we add .days.
  • Save the outcome to a list, although of course you could do whatever you wanted with the output.
  • Related