Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Pandas Series.dt.day attribute

Pandas Series.dt.day attribute

Pandas Universal Functions Common Pandas functions


Series.dt.day is a Pandas attribute used to **extract the day (date) from a datetime**. It is part of the dt accessor and can quickly extract the day of the month (1-31) from a Series of datetime type.

In time series data analysis, analyzing by day is a common need, such as examining specific days of each month or identifying periodic patterns.dt.day attribute makes such operations simple and efficient.

Word meaning: day means "day", that is, it returns the day in a date (the day of the month).


Basic syntax and parameters

Series.dt.day is an attribute of the dt accessor of Series, used to extract the day.

Syntax format



Series.dt.day

Parameter Description

This attribute requires no arguments; simply access the day information of a datetime Series.

Return value description


Example

Let us thoroughly master Series.dt.day through a series of examples from simple to complex.

Example 1: Basic usage - extracting the day

Example

import

pandas

as

pd

1. Create a Series of datetimes

print

(

"=== Create a 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 the day

print

(

"n=== Extract the day with dt.day ==="

)

days

=

datetime_series.

dt

.

day

print

(

"Day:"

)

print

(

days

)

3. Extract year, month, and day together

print

(

"n=== Extract year, month, and day ==="

)

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 each month has

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 of a Leap Year

print

(

"n=== Days in February of a Leap Year ==="

)

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}"

)

Result:



=== 创建日期时间 Series ===

0   2023-01-15

1   2023-02-20

2   2023-03-05

3   2023-04-30

4   2023-05-25

5   2023-12-31

dtype: datetime64[ns]



=== 使用 dt.day 提取天 ===

天:

0    15

1    20

2     5

3    30

4    25

5    31

dtype: int64



=== 同时提取年月日 ===

       原始日期  年  月  日

0 2023-01-15  2023  1  15

1 2023-02-20  2023  2  20

2 2023-03-05  2023  3   5

3 2023-04-30  2023  4  30

4 2023-05-25  2023  5  25

5 2023-12-31  2023 12  31



=== 各月的天数 ===

         月份  天数

0  2023-01-01  31

1  2023-02-01  28

2  2023-03-01  31

3  2023-04-01  30

4  2023-05-01  31

5  2023-06-01  30

6  2023-07-01  31

7  2023-08-01  31

8  2023-09-01  30

9  2023-10-01  31

10 2023-11-01  30

11 2023-12-01  31



=== 闰年2月天数 ===

2024年2月天数: 29

2023年2月天数: 28

Code analysis:

  1. dt.day Returns an integer from 1 to 31 representing the day of the month.
  2. You can extract the year, month, and day together to create a new DataFrame.
  3. days_in_month The attribute retrieves the number of days in each month, which is useful for handling end-of-month dates.
  4. 2024 is a leap year with 29 days in February; 2023 is a common year with 28 days in February.

Example 2: Filtering and Analysis by Day

Example

import

pandas

as

pd

import

numpy

as

np

Create a dataset containing dates

print

(

"=== Create Transaction Data ==="

)

np.

random

.

seed

(

100

)

Generate 30 days of data

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 days

df

[

'day'

]

=

df

[

'date'

]

.

dt

.

day

print

(

df.

head

(

15

)

)

Filter records for specific days (such as the 15th of each month)

print

(

"n=== Transactions on the 15th of Each Month ==="

)

day_15

=

df

[

df

[

'day'

]

==

15

]

print

(

day_15

)

Filter the first half and second half of the month

print

(

"n=== First Half vs Second Half of the Month ==="

)

df

[

'half'

]

=

df

[

'day'

]

.

apply

(

lambda

x:

'First Half'

if

x

<=

15

else

'Second Half'

)

half_stats

=

df.

groupby

(

'half'

)

[

'transactions'

]

.

agg

(

[

'sum'

,

'mean'

]

)

.

round

(

2

)

half_stats.

columns

=

[

'Total Transactions'

,

'Average Transactions'

]

print

(

half_stats

)

Aggregate by day

print

(

"n=== Average Revenue by Day ==="

)

daily_avg

=

df.

groupby

(

'day'

)

[

'revenue'

]

.

mean

(

)

.

round

(

2

)

print

(

daily_avg

)

Find the day with the highest revenue

print

(

"n=== Days with the Highest and Lowest Revenue ==="

)

max_day

=

df.

loc

[

df

[

'revenue'

]

.

idxmax

(

)

]

min_day

=

df.

loc

[

df

[

'revenue'

]

.

idxmin

(

)

]

print

(

f

"Highest revenue: {max_day['date'].date()}, amount {max_day['revenue']}"

)

print

(

f

"Lowest revenue: {min_day['date'].date()}, amount {min_day['revenue']}"

)

Result:



=== 创建交易数据 ===

         date  transactions  revenue  day

0  2023-03-01             73  16200    1

1  2023-03-02            163  18800    2

2  2023-03-03             76   9600    3

3  2023-03-04             83  10500    4

4  2023-03-05            136  16200    5

5  2023-03-06             86  11700    6

6  2023-03-07             87  13400    7

7  2023-03-08            168  14200    8

8  2023-03-09            163  15800    9

9  2023-03-10             82  11000   10

10 2023-03-11            106  14600   11

11 2023-03-12            152  15900   12

12 2023-03-13            数据截断...



=== 每月15号的交易 ===

        date  transactions  revenue  day

14  2023-03-15            104  12900   15



=== 上半月 vs 下半月 ===

        总交易数  平均交易数

下半月   2117  111.42

上半月   1873  117.06



=== 按天统计平均收入 ===

day

1     16200.00

2     18800.00

...



=== 收入最高和最低的天 ===

最高收入: 2023-03-02,金额 18800

最低收入: 2023-03-03,金额 9600

Code analysis:

Example 3: Handling End-of-Month Dates

Example

import

pandas

as

pd

1. Handling the Last Day of Different Months

print

(

"=== Last Day of Each Month ==="

)

dates

=

pd.

date_range

(

'2023-01-01'

,

periods

=

12

,

freq

=

'MS'

)

print

(

"First day of each month:"

)

print

(

dates

)

Get the last day of each month

last_days

=

dates + pd.

offsets

.

MonthEnd

(

0

)

print

(

"nLast day of each month:"

)

print

(

last_days

)

2. Determine whether it is the end of the month

print

(

"n=== Determine Whether It Is the End of the Month ==="

)

test_dates

=

pd.

Series

(

[

   

'2023-01-30'

,

 

January 30 (not the end of the month)

   

'2023-01-31'

,

 

January 31 (the end of the month)

   

'2023-02-28'

,

 

February 28 (non-leap year)

   

'2023-04-30'

,

 

April 30 (the end of the month)

]

)

dt_series

=

pd.

to_datetime

(

test_dates

)

is_month_end

=

dt_series.

is_month_end

result

=

pd.

DataFrame

(

{

   

'Date'

: dt_series

,

   

'Is End of Month'

: is_month_end

}

)

print

(

result

)

3. Handling Start-of-Month Dates

print

(

"n=== Determine Whether It Is the Start of the Month ==="

)

is_month_start

=

dt_series.

is_month_start

result

[

'Is Start of Month'

]

=

is_month_start

print

(

result

)

4. Handling Inconsistent Month Lengths

print

(

"n=== Handling Inconsistent Month Lengths ==="

)

dates_to_check

=

pd.

Series

(

[

   

'2023-01-31'

,

 

Valid date

   

'2023-02-30'

,

 

Invalid date (February has no 30th day)

]

)

Attempt conversion and handle invalid dates

try

:

    valid_dates

=

pd.

to_datetime

(

dates_to_check

,

errors

=

'coerce'

)

   

print

(

"Converted dates:"

)

   

print

(

valid_dates

)

   

print

(

"nDays Corresponding to Each Date:"

)

   

print

(

valid_dates.

dt

.

day

)

except

Exception

as

e:

   

print

(

f

"Error: {e}"

)

Result:



=== 各月最后一天 ===

First day of every month:

DatetimeIndex(['2023-01-01', '2023-02-01', '2023-03-01', '2023-04-01',

               '2023-05-01', '2023-06-01', '2023-07-01', '2023-03-01',

               '2023-09-01', '2023-10-01', '2023-11-01', '2023-12-01'],

              dtype='datetime64[ns]', freq=None)



Last day of the month:

DatetimeIndex(['2023-01-31', '2023-02-28', '2023-03-31', '2023-04-30',

               '2023-05-31', '2023-06-30', '2023-07-31', '2023-03-31',

               '2023-09-30', '2023-10-31', '2023-11-30', '2023-12-31'],

              dtype='datetime64[ns]', freq=None)



=== 判断是否为月末 ===

         日期  是否为月末

0 2023-01-30    False

1 2023-01-31     True

2 2023-02-28     True

3 2023-04-30     True



=== 判断是否为月初 ===

         日期  是否为月末  是否为月初

0 2023-01-30    False    False

1 2023-01-31    False    False

2 2023-02-28    False    False

3 2023-04-30    False    False



=== 月份天数不一致的处理 ===

Converted date:

0   2023-01-31

1          NaT

Name: date, dtype: datetime64[ns]



Days corresponding to each date:

0    31.0

1     NaN

Code analysis:

Notes

Important note:

  • Series.dt.day It can only be used with a Series of dtype datetime64.
  • The returned day range is 1-31, with the exact maximum depending on the month (at most 28/29 days in February, 30 days in April/June/September/November, and 31 days in other months).
  • You can use the dt.days_in_month Get the number of days in each month.
  • When working with data containing missing values (NaT),dt.day NaT is returned at the corresponding positions.

  • Pandas Common Functions Common Pandas functions