Reputation: 13
I'm relatively new to the python programming language and have set my on little project as a goal to learn python. Now I'm struggling with two (probably) little problems. In general I would like to compare birthday dates with the current date. If the birthday date in column "birthday" = today the name of the person should be printed within a sentence.
The first problem I have is that i need to compare day and month but not the year and I can't figure it out. The second problem is that I am not able to figure out how I can print the name of the person which birthday is today. What I tried is to go via the index "first name" but then the whole index will be printed. Table and code are attached. Thank you in advance for your help.
Last Name | First Name | Birthday |
---|---|---|
Love | David | 07.05.1986 |
Hate | Robert | 17.12.1976 |
Peace | Frank | 02.09.2021 |
The last one with birthday 02.09.2021 is just modified to have a true outcome.
Input
from datetime import date
from datetime import timedelta
from openpyxl import load_workbook
wb=load_workbook("U:\\Python\\untitled\\Birthdaylist.xlsx")
ws=wb["Sheet1"]
import pandas as pd
df=pd.DataFrame(ws.values)
df.columns=df.iloc[[0]].values.tolist()[0]
df=df[1:]
df.head()
for i in df["Birthday"]:
if i.date()< date.today():
print("It's no one's birthday today!")
if i.date() == date.today():
print("Today is ",(df["First Name"]), "'s birthday")
if date.today() < i.date() < (date.today()+ timedelta(days=3)):
print(df["First Name"], "'s birthday is on ", df["Birthday"].date, ".")
Output
It's no one's birthday today!
It's no one's birthday today!
It's no one's birthday today!
It's no one's birthday today!
It's no one's birthday today!
Today is 1 David
2 Robert
3 Frank
4 Julia
5 Marie
Name: First Name, dtype: object 's birthday
Upvotes: 1
Views: 245
Reputation: 120559
First, compute the birthday for the current year then subtract the current date to get the difference in days:
today = pd.Timestamp.today().date()
df['Birthday'] = pd.to_datetime(df['Birthday'], format='%d.%m.%Y')
df['When'] = df['Birthday'].apply(lambda x: x.replace(year=today.year))
df['Days'] = df['When'].dt.date.sub(today).dt.days
At this point, your dataframe looks like:
>>> df
Last Name First Name Birthday When Days
0 Love David 1986-09-04 2021-05-07 2
1 Hate Robert 1976-12-17 2021-12-17 106
2 Peace Frank 2021-09-02 2021-09-02 0
Now you can filter your dataframe:
# Birthday today
>>> df.loc[df['Days'] == 0, 'First Name']
2 Frank
Name: First Name, dtype: object
# Birthday in next 3 days
>>> df.loc[df['Days'].between(1, 3), 'First Name']
0 David
Name: First Name, dtype: object
Upvotes: 0
Reputation: 3299
I'm assuming your birthday column is strings rather than date/time, if so you can split it up by the '.'
charecter into day month and year using .str.split('.', expand=True)
and converting those columns to inegers.
You can then use datetime to get todays date, and use that in pandas.loc
to filter on month and day to get who's birthday it is. I've used .iloc[0]
to get just the string of the name, but if there are more than 1 birthdays on that day, then you're probably better returning a list using .to_list()
instead and iterate through that to print the names of who's birthday it is today. If no birthdays today, then the Name variable will return empty (i.e. len(Name) == 0
).
import pandas as pd
import datetime
df = pd.DataFrame({'Last Name' : ['Love', 'Hate', 'Peace'],
'First Name' : ['David', 'Robert', 'Frank'],
'Birthday' : ['07.05.1986', '17.12.1976', '02.09.2021']})
df[['Day', 'Month', 'Year']] = df['Birthday'].str.split('.', expand=True).astype(int)
Today = datetime.datetime.today()
Name = df.loc[(df['Day'] == Today.day) & (df['Month'] == Today.month), 'First Name'].iloc[0]
Upvotes: 0
Reputation: 262359
Do you want to do this in pandas (looks like it according to the tags)?
# read file
df = pd.read_excel('Birthdaylist.xlsx')
# ensure datetime
df['Birthday'] = pd.to_datetime(df['Birthday'], dayfirst=True)
# set up condition for birthday
today = pd.to_datetime('today', dayfirst=True)
has_birthday = ( df['Birthday'].dt.month.eq(today.month)
&df['Birthday'].dt.year.eq(today.year)
)
# slice dataframe
df[has_birthay]
output:
Last Name First Name Birthday
2 Peace Frank 2021-09-02
Printing part:
if len(df[has_birthday])>0:
for _, row in df[has_birthday].iterrows():
print(f"Today is {row['First Name']}'s birthday") # NB. prints several rows if multiple birthdays
else:
print("It's no one's birthday today!")
Upvotes: 1