Reputation: 69
I have a datetime column called 'Start Time'
I am trying to find entries with a specific weekday name based on user input.
The user input is a String and can be Sunday, Monday,...Saturday. So if Sunday is input I want to find all entries that have Sunday as the day, regardless of the month or year.
Here is my code:
user_day = input('Input the name of the day.user_day.')
print(df[df['Start Time'].dt.weekday == dt.datetime.strptime(user_day, '%A')])
The output is: Empty DataFrame Columns: [Unnamed: 0, Start Time, End Time, Trip Duration, Start Station, End Station, User Type] Index: []
Upvotes: 1
Views: 249
Reputation: 8559
pandas.Series.dt.weekday
: The day of the week with Monday=0,
Sunday=6pandas.Series.dt.weekday_name
: The name of day in a week (e.g.,: Friday)Pay attention to user input. You are loading a string
, you don't need to convert such a string to datetime
using strptime
.
You just need to match the weekday_name
of the datetimelike
in your DF with user input. It's a string matching.
print(df[df['Start Time'].dt.weekday_name == user_day])
Upvotes: 0
Reputation: 862851
Use weekday_name
or strftime
with same format:
print(df[df['Start Time'].dt.weekday_name == user_day])
Or:
print(df[df['Start Time'].dt.strftime('%A') == user_day])
Verify:
df = pd.DataFrame({'Start Time':pd.date_range('2015-01-01 15:02:45', periods=10)})
print (df)
Start Time
0 2015-01-01 15:02:45
1 2015-01-02 15:02:45
2 2015-01-03 15:02:45
3 2015-01-04 15:02:45
4 2015-01-05 15:02:45
5 2015-01-06 15:02:45
6 2015-01-07 15:02:45
7 2015-01-08 15:02:45
8 2015-01-09 15:02:45
9 2015-01-10 15:02:45
user_day = 'Monday'
print(df[df['Start Time'].dt.weekday_name == user_day])
Start Time
4 2015-01-05 15:02:45
print (df['Start Time'].dt.weekday_name)
0 Thursday
1 Friday
2 Saturday
3 Sunday
4 Monday
5 Tuesday
6 Wednesday
7 Thursday
8 Friday
9 Saturday
Name: Start Time, dtype: object
print (df['Start Time'].dt.strftime('%A'))
0 Thursday
1 Friday
2 Saturday
3 Sunday
4 Monday
5 Tuesday
6 Wednesday
7 Thursday
8 Friday
9 Saturday
Name: Start Time, dtype: object
Upvotes: 2