YouTip LogoYouTip

Pandas Series Dt Day

[![Image 1: PandasCommon Functions](#) PandasCommon Functions](#) * * * `Series.dt.day` is a property in Pandas used to **extract the day (date) from datetime**. It is part of the dt accessor and can quickly extract which day of the month (1-31) from a datetime-type Series. In time series data analysis, analyzing by day is a common requirement, such as analyzing specific days of each month or identifying periodic patterns. The `dt.day` property makes these operations simple and efficient. **Word Definition**: `day` means "day", returning the day part of a date (the day of the month). * * * ## Basic Syntax and Parameters `Series.dt.day` is a property of the Series dt accessor, used to extract the day. ### Syntax Format Series.dt.day ### Parameter Description This property does not require any parameters; it directly accesses the day information from a datetime Series. ### Return Value Description * **Return Value**: Returns an integer Series containing the day (1-31). * **Effect**: Extracts the day part from a datetime64-type Series and returns integers from 1 to 31. * * * ## Examples Let's go through a series of examples from simple to complex to fully master the usage of `Series.dt.day`. ### Example 1: Basic Usage - Extracting Days ## Example import pandas as pd # 1. Create a Series with datetime print("=== Creating Datetime Series ===") dates = pd.Series([ '2023-01-15', '2023-02-20', '2023-03-05', '2023-04-30', '2023-05-25', '2023-12-31' ]) # Convert to datetime type datetime_series = pd.to_datetime(dates) print("Original Dates:") print(datetime_series) # 2. Use dt.day to extract days print("n=== Using dt.day to Extract Days ===") days = datetime_series.dt.day print("Days:") print(days) # 3. Extract year, month, and day simultaneously print("n=== Extracting Year, Month, and Day Simultaneously ===") datetime_series = pd.to_datetime(dates) df = pd.DataFrame({ 'Original Date': datetime_series, 'Year': datetime_series.dt.year, 'Month': datetime_series.dt.month, 'Day': datetime_series.dt.day }) print(df) # 4. Check how many days are in each month print("n=== Number of Days in Each Month ===") dates_full = pd.date_range('2023-01-01', periods=12, freq='MS') days_in_month = dates_full.dt.days_in_month print(pd.DataFrame({ 'Month': dates_full, 'Days': days_in_month })) # 5. Days in February during leap years print("n=== Days in February During Leap Years ===") leap_feb = pd.Timestamp('2024-02-01').days_in_month print(f"Days in February 2024: {leap_feb}") non_leap_feb = pd.Timestamp('2023-02-01').days_in_month print(f"Days in February 2023: {non_leap_feb}") **Output:** === Creating Datetime Series ===0 2023-01-151 2023-02-202 2023-03-053 2023-04-304 2023-05-255 2023-12-31 dtype: datetime64=== Using dt.day to Extract Days ===Days:0 151 202 53 304 255 31 dtype: int64 === Extracting Year, Month, and Day Simultaneously === Original Date Year Month Day0 2023-01-15 2023 1 151 2023-02-20 2023 2 202 2023-03-05 2023 3 53 2023-04-30 2023 4 304 2023-05-25 2023 5 255 2023-12-31 2023 12 31=== Number of Days in Each Month === Month Days0 2023-01-01 311 2023-02-01 282 2023-03-01 313 2023-04-01 304 2023-05-01 315 2023-06-01 306 2023-07-01 317 2023-08-01 318 2023-09-01 309 2023-10-01 3110 2023-11-01 3011 2023-12-01 31=== Days in February During Leap Years ===Days in February 2024: 29Days in February 2023: 28 **Code Explanation:** 1. `dt.day` returns integers from 1 to 31, representing the day of the month. 2. You can extract year, month, and day simultaneously to create a new DataFrame. 3. The `days_in_month` property can get the number of days in a month, useful for handling end-of-month dates. 4. 2024 is a leap year, so February has 29 days; 2023 is a regular year, so February has 28 days. ### Example 2: Filtering and Analyzing by Day ## Example import pandas as pd import numpy as np # Create a dataset with dates print("=== Creating Transaction Data ===") np.random.seed(100) # Generate data for 30 days dates = pd.date_range('2023-03-01', periods=30, freq='D') df = pd.DataFrame({ 'date': dates, 'transactions': np.random.randint(50,200,30), 'revenue': np.random.randint(5000,20000,30) }) # Extract day df['day']= df['date'].dt.day print(df.head(15)) # Filter records on specific days (e.g., 15th of each month) print("n=== Transactions on the 15th of Each Month ===") day_15 = df[df['day']==15] print(day_15) # Filter first and second halves of the month print("n=== First Half vs Second Half ===") df['half']= df['day'].apply(lambda x: 'First Half' if x **Important Notice:** > > > * `Series.dt.day` can only be used on Series with datetime64 type. > * The returned day numbers range from 1 to 31, with the maximum depending on the month (February has a maximum of 28/29 days, April/Jun/Sept/Nov have 30 days, others have 31 days). > * You can use `dt.days_in_month` to get the number of days in a month. > * When dealing with missing values (NaT), `dt.day` will return NaT at the corresponding positions. * * PandasCommon Functions](#)
← Pandas Df PivotPandas Series Dt Year β†’