Python Pandas (Excel) datasheet code issue

Viewed 75

I have imported an excel (.xlsx) spreadsheet into my python code (using Pandas) and want to extract data from it and the spreadsheet contains the following;

DATE:        Lecture1:   Lecture2:
16/07/2020   09:30       11:00
17/07/2020   09:45       11:30
18/07/2020   09:45       11:00
19/07/2020   10:00       14:30
20/07/2020   09:30       14:45

How can I create the part of the code so that if "now = date.today()", then "print" the row of my lectures for that day...

I have the following;

import pandas as pd

data = pd.read_excel(r'/home/timetable1.xlsx')
data["Date"] = pd.to_datetime(data["Date"]).dt.strftime("%d-%m-%Y")
df = pd.DataFrame(data)
print (df)

This prints out the whole timetable as shown below (note the format changes slightly);

         Date  Lecture1  Lecture2
0  16-07-2020  09:30:00  11:00:00
1  17-07-2020  09:45:00  11:30:00
2  18-07-2020  09:45:00  11:00:00
3  19-07-2020  10:00:00  14:30:00
4  20-07-2020  09:30:00  14:45:00

So I am not sure what the part of the code will be to determine 'todays' date and show only 'todays' lecture times for example something like this maybe;

now = date.today()
now.strftime("%d-%m-%y")
if ["Date" == now]:
    print ('timetable1.xlsx' index_col=now)

I am new to coding so not very good at it. The above code is wrong I know I can't think of a way to display the info.

So my desired output that I want;

      Date  Lecture1  Lecture2
18-07-2020  09:45:00  11:00:00

Your input would be much appreciated.

3 Answers

Check this:

data['Date'] = pd.to_datetime(data['Date']).dt.strftime("%d-%m-%Y")
now = pd.to_datetime('today').strftime("%d-%m-%Y")
print(data[data['Date'] == now])

Here you go:

from datetime import date
df['DATE'] = pd.to_datetime(df.DATE, format='%d/%m/%Y')
print(df[df.DATE == pd.to_datetime(date.today())])

Output (It's 19th for me)

        DATE Lecture1 Lecture2
3 2020-07-19    10:00    14:30

What you can do is take in the current date in the correct format as the dataset like this:

today=date.today()
compare=today.strftime("%d-%m-%y")

And the do a .loc command on the dataframe

df.loc[df['Date'] == compare]
Related