We are given a CSV file containing names and birthdays, we have to output who's birthday is next in function.
kept getting a local unbound error, not sure how to fix it, basically trying to read the file, check the dates, find which date is next, then return the name connected with that date
birthdates.csv:
Draven Brock,01/21/1952
Easton Mclean,09/02/1954
Destiny Pacheco,10/10/1958
Ariella Wood,12/20/1961
Keely Sanders,08/03/1985
Bryan Sloan,04/06/1986
Shannon Brewer,05/11/1986
Julianne Farrell,01/29/2000
Makhi Weeks,03/20/2000
Lucian Fields,08/02/2010
Function Call:
nextBirthdate("birthdates.csv", "01/01/2022")
Output:
Draven Brock
def nextBirthdate(filename, date):
f = open(filename, 'r')
lines = f.readlines()
f.close()
for i in range(len(lines)):
lines[i] = lines[i].strip()
# split for the target date
date = line.split('/')
month = date[0]
day = date[1]
diff = 365
diffDays = 0
bName = None
bDays = []
for line in lines:
items = line.split(",")
names = items[0]
# split the date apart between month, day, and year
bDay = items[1].split("/")
bDays.append(bDay)
for d in bDays:
if bDay[0] == month:
if bDay[1] > day:
diffDays = int(bDay[0]) - int(day)
if diffdays < diff:
diff = diffDays
bName = name
elif bDay[0] > month:
diffDays = ((int(bDay[0]) - 1) * 31) int(day)
if diffDays < diff:
diff = diffDays
bName = name
if bName == None:
return nextBirthdate(filename, "01/01/2022")
return bName
if __name__ == "__main__":
filename = "birthdates.csv"
date = "12/31/2022"
print(nextBirthdate(filename, date))
CodePudding user response:
Welcome to stack overflow. The way to do this is
Read in your CSV data
Convert the data to e.g. a pandas DataFrame
2a. I suggest you convert the dates to e.g. pd.Timestamp and not keep them as strings to avoid bad things happening when comparing
Sort the DataFrame based on dates, or find the row with the min value, its up to you
How to do each of those things is its own question, that has at least one answer already in stack overflow and other places, so you probably do not need to ask a new one, just search for it.
CodePudding user response:
So here I got this - You just want to know who's next bday it is and want the name
of the person based on the CSV
file. Below code should work
import pandas as pd
from datetime import date
def nextBirthdate(file, inp_date):
d,m,y = [int(x) for x in inp_date.split('/')]
df = pd.read_csv('file.csv', header=None)
df[1] = pd.to_datetime(df[1])
df[1] = df[1].apply(lambda x: x.replace(year=y))
inp_date = date(y,m,d)
df['Diff'] = (df[1].dt.date - inp_date).dt.days
return df.sort_values(by=['Diff'])[0].values[0]
nextBirthdate("birthdates.csv", "01/01/2022")