说明

对于 datetime64、timedelta64、period 类型的 Series,可通过 .dt 访问器提取时间组件,返回一个普通 Series(或布尔/类别 Series)。

import pandas as pd
 
s = pd.Series(pd.date_range('2026-08-19 13:05:30', periods=3, freq='D'))
print(s.dt)
# <pandas.core.accessor.PandasDelegate object>

日期组件

说明

提取时间戳的各组成部分。

print(s.dt.year)          # 0    2026 ...
print(s.dt.month)         # 0    8 ...
print(s.dt.day)           # 0    19 ...
print(s.dt.hour)          # 0    13 ...
print(s.dt.minute)        # 0    5 ...
print(s.dt.second)        # 0    30 ...
print(s.dt.microsecond)   # 0    0 ...
print(s.dt.nanosecond)    # 0    0 ...

日历属性

说明

提取星期、年积日、季度、月天数等日历信息。

print(s.dt.week)            # 周序号(已弃用,建议用 isocalendar)
print(s.dt.weekofyear)      # 周序号别名(已弃用)
print(s.dt.dayofyear)       # 0    231 ...
print(s.dt.day_of_year)     # 与 dayofyear 相同
print(s.dt.quarter)         # 0    3 ...
print(s.dt.days_in_month)   # 0    31 ...
print(s.dt.daysinmonth)     # 与 days_in_month 相同

弃用提示

s.dt.week 与 s.dt.weekofyear 已在 pandas 2.x 弃用,请改用 s.dt.isocalendar().week。

星期属性

print(s.dt.dayofweek)      # 0    2(周一=0 ... 周日=6)
print(s.dt.day_of_week)    # 与 dayofweek 相同
print(s.dt.weekday)        # 与 dayofweek 相同

判断属性

说明

返回布尔 Series,判断该时间是否处于某个日历边界。

print(s.dt.is_month_start)     # 是否月初
print(s.dt.is_month_end)       # 是否月末
print(s.dt.is_quarter_start)   # 是否季初
print(s.dt.is_quarter_end)     # 是否季末
print(s.dt.is_year_start)      # 是否年初
print(s.dt.is_year_end)        # 是否年末
print(s.dt.is_leap_year)       # 是否闰年

方法

说明

.dt 提供多种转换与格式化方法。

方法说明适用类型
date()返回 datetime.date 对象datetime
time()返回 datetime.time 对象datetime
timetz()返回带时区的 datetime.time 对象datetime
tz返回时区信息datetime
freq返回频率对象datetime / period
freqstr返回频率字符串datetime / period
strftime(fmt)按格式输出字符串datetime / period
round(freq)按频率取整(四舍五入)datetime / timedelta
floor(freq)按频率向下取整datetime / timedelta
ceil(freq)按频率向上取整datetime / timedelta
month_name()返回月份名称(如 'August')datetime
day_name()返回星期名称(如 'Wednesday')datetime
to_period(freq)转换为 Perioddatetime
to_pydatetime()转 Python datetime 对象datetime / timedelta
normalize()时间归一到 0 点datetime
components返回时间差各组件 DataFrametimedelta
total_seconds()返回总秒数timedelta
to_timestamp()转换为时间戳period

示例

# datetime 方法
print(s.dt.date())
print(s.dt.time())
print(s.dt.strftime('%Y-%m-%d %H:%M'))
print(s.dt.round('D'))
print(s.dt.floor('h'))
print(s.dt.ceil('D'))
print(s.dt.month_name())
print(s.dt.day_name())
print(s.dt.to_period('M'))
print(s.dt.normalize())
 
# timedelta 方法
td = pd.Series(pd.to_timedelta(['1 days 02:00:00', '2 days 04:00:00']))
print(td.dt.components)
#    days  hours  minutes  seconds  milliseconds  microseconds  nanoseconds
# 0     1      2        0        0             0             0            0
# 1     2      4        0        0             0             0            0
 
print(td.dt.total_seconds())
# 0    93600.0
# 1    187200.0
 
# period 数据
p = pd.Series(pd.period_range('2026-01', periods=2, freq='M'))
print(p.dt.to_timestamp())
print(p.dt.freqstr)

🔗 相关链接