Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Pandas - Get the Day of the week the period lies in
To get the day of the week that a Period falls on, use the period.dayofweek property. This returns an integer where Monday=0, Tuesday=1, ..., Sunday=6.
Importing Required Libraries
At first, import the required libraries ?
import pandas as pd
Creating Period Objects
The pandas.Period represents a period of time. Creating two Period objects ?
period1 = pd.Period("2021-09-18")
period2 = pd.Period(freq='D', year=2021, month=9, day=22, hour=4, minute=55)
print("Period1...\n", period1)
print("Period2...\n", period2)
Period1... 2021-09-18 Period2... 2021-09-22
Getting Day of Week
Get the day of week from two Period objects using the dayofweek property ?
import pandas as pd
# Creating Period objects
period1 = pd.Period("2021-09-18")
period2 = pd.Period(freq='D', year=2021, month=9, day=22, hour=4, minute=55)
# Get the day of week from Period objects
res1 = period1.dayofweek
res2 = period2.dayofweek
# Display results - Monday=0, Tuesday=1, ..., Sunday=6
print("Period1 (2021-09-18) day of week:", res1)
print("Period2 (2021-09-22) day of week:", res2)
# Convert to actual day names for clarity
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
print("Period1 falls on:", days[res1])
print("Period2 falls on:", days[res2])
Period1 (2021-09-18) day of week: 5 Period2 (2021-09-22) day of week: 2 Period1 falls on: Saturday Period2 falls on: Wednesday
Understanding the Output
The dayofweek property returns integers representing days of the week:
- 0 = Monday
- 1 = Tuesday
- 2 = Wednesday
- 3 = Thursday
- 4 = Friday
- 5 = Saturday
- 6 = Sunday
Conclusion
Use the dayofweek property to get the day of the week as an integer (0-6). You can map these integers to day names for better readability in your applications.
Advertisements
