I have the following code:
for dictionary in ministers:
if(math.floor((datetime.date.today() - dictionary[3]).days/365.25) <50):
print(dictionary[1], dictionary[2], math.floor((datetime.datetime.today() - dictionary[3]).days/365.25))
I am supposed to take today's date and subtract that with a date given in a list of dictionaries. Here is that list of dictionaries:
ministers = [{1: "Alexander", 2: "De Croo", 3: "3-11-1975", 4: "Vilvoorde", 5: "Open Vld"},
{1: "Sophie", 2: "Wilmès", 3: "15-01-1975", 4: "Elsene", 5: "MR"},
{1: "Frank", 2: "Vandenbroucke", 3: "21-10-1955", 4: "Leuven", 5: "sp.a"},
{1: "Petra", 2: "De Sutter", 3: "10-6-1963", 4: "Oudenaarde", 5: "groen"},
{1: "Sammy", 2: "Mahdi", 3: "21-9-1988", 4: "Elsene", 5: "CD&V"},
{1: "Zakia", 2: "Khattabi", 3: "15-1-1976", 4: "Sint-Joost-ten-Node", 5: "Ecolo"},
{1: "Ludivine", 2: "Dedonder", 3: "17-3-1977", 4: "Doornik", 5: "PS"},
{1: "Karine", 2: "Lalieux", 3: "4-5-1964", 4: "Anderlecht", 5: "PS"},]
If the resulted number is smaller than 50 than I am supposed to indicate that. But it is impossible to subtract 2 dates from eachother like this, I'm aware of that but I can't find any fix or way around this. I'm still very new to python and programming in general.
This is the resulting error: TypeError: unsupported operand type(s) for -: 'datetime.date' and 'str'
I have tried converting the dates into an int or float, but this doesn't work either.
CodePudding user response:
As the error message is saying, your subtraction does not work because you are trying to subtract a string from a date, and python does not know how to do it.
The solution is to subtract date from a date, like in this example:
date_1 = datetime.date(2019, 1, 1)
date_2 = datetime.date(2018, 11, 10)
print(date_2 - date_1)
# prints -52 days, 0:00:00
Now to get there, you will need to convert the strings such as "15-1-1975" to dates. For this use the following function:
date = datetime.datetime.strptime("15-1-1976", "%d-%m-%Y")
CodePudding user response:
This is an approximate solution to your problem:
from datetime import datetime, timedelta
today = datetime.now()
ministers = [
{1: "Alexander", 2: "De Croo", 3: "3-11-1975", 4: "Vilvoorde", 5: "Open Vld"},
{1: "Sophie", 2: "Wilmès", 3: "15-01-1975", 4: "Elsene", 5: "MR"},
{1: "Frank", 2: "Vandenbroucke", 3: "21-10-1955", 4: "Leuven", 5: "sp.a"},
{1: "Petra", 2: "De Sutter", 3: "10-6-1963", 4: "Oudenaarde", 5: "groen"},
{1: "Sammy", 2: "Mahdi", 3: "21-9-1988", 4: "Elsene", 5: "CD&V"},
{1: "Zakia", 2: "Khattabi", 3: "15-1-1976", 4: "Sint-Joost-ten-Node", 5: "Ecolo"},
{1: "Ludivine", 2: "Dedonder", 3: "17-3-1977", 4: "Doornik", 5: "PS"},
{1: "Karine", 2: "Lalieux", 3: "4-5-1964", 4: "Anderlecht", 5: "PS"}
]
for minister in ministers:
dob = datetime.strptime(minister[3], '%d-%m-%Y')
if today - dob < timedelta(days=18250):
print(f"Minister {minister[1]} is younger than 50")