df.head()
Log_ID | dt | dept | activity | eqpt | |
---|---|---|---|---|---|
0 | 1000 | 2021-04-24 | dept1 | cleaning | UPS |
1 | 1001 | 2021-04-25 | dept3 | repair | Generator |
2 | 1002 | 2021-04-26 | dept1 | cheking | AC |
3 | 1003 | 2021-04-27 | dept3 | painting | Generator |
4 | 1004 | 2021-04-28 | dept1 | cleaning | UPS |
c_year=pd.to_datetime('now').year #current year
print(df[df['dt'].dt.year==c_year].count()[0])
#print(df[df['dt'].dt.year==2022].count())
Output
115
You can un-comment the other line and check how all columns are listed. print(df.set_index('dt')['2022-03'])
The number of records.
print(df.set_index('dt')['2020-03'].count())
print(df.loc[df['Log_ID']==1012])
Output
Log_ID dt dept activity eqpt
12 1012 2021-05-08 Dept3 Checking Fan
max_date=df.loc[df['eqpt']=='Pump']['dt'].max()
#print(max_date)
print(df.loc[df['dt']==max_date])
Output
Log_ID dt dept activity eqpt
361 1361 2022-04-22 Dept3 Cleaning Pump
#print(df.set_index('dt')['2021-04':'2021-06']) # total list
print(df.set_index('dt')['2021-04':'2021-06'].count())# Total Number
Output
66
max_date=df.loc[df['eqpt']=='Pump']['dt'].max()
#print(max_date)
print(df.loc[df['dt']==max_date])
today=pd.to_datetime('now')
print( "Days difference = ", ( today - max_date))
Output
Log_ID dt dept activity eqpt
364 1364 2022-04-25 Dept3 Checking Pump
Days difference = 0 days 10:13:00.490353
today=pd.to_datetime('now')
#today=pd.to_datetime('2022-04-12') # change this date YYYY-MM-DD
new_day=today-datetime.timedelta(7)
print(df[(df['dt']>new_day)])
Output
Log_ID dt dept activity eqpt
358 1358 2022-04-19 Dept2 Inspection Fan
359 1359 2022-04-20 Dept4 Checking Battery
360 1360 2022-04-21 Dept2 Painting AC
361 1361 2022-04-22 Dept1 Cleaning AC
362 1362 2022-04-23 Dept4 Cleaning Server
363 1363 2022-04-24 Dept4 Cleaning UPS
364 1364 2022-04-25 Dept4 Painting AC
print(df[df['dt'].dt.weekday==2])
To check the weekday we can add one more column saying weekday. We can add our format by using strftime
df['weekday']=df['dt'].dt.strftime('%A')
Read more on groupby() here
print(df.groupby(df['dt'].dt.year).count())
print(df.groupby(df['dt'].dt.year).count()['Log_ID'])
print(df.groupby(df['dt'].dt.month).count())
print(df.groupby([df['dt'].dt.year,df['dt'].dt.month]).count())
Pandas Pandas date & time Basic Exercise using datetime 3-2
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.