Python Pandas - 从 Period 对象获取一年中的某一天
pythonpandasserver side programmingprogramming更新于 2026/1/2 13:32:17
要从 Period 对象获取一年中的某一天,请使用 period.dayofyear 属性。
首先,导入所需的库 −
import pandas as pd
pandas.Period 表示一段时间。创建两个 Period 对象 −
period1 = pd.Period("2020-09-23")
period2 = pd.Period(freq="D", year = 2021, month = 7, day = 16, hour = 2,minute = 35)
显示 Period 对象 −
print("Period1...\n", period1)
print("Period2...\n", period2)
从两个 Period 对象中获取一年中的某一天 −
res1 = period1.dayofyear res2 = period2.dayofyear
示例
以下是代码 −
import pandas as pd
# pandas.Period 表示一段时间
# 创建两个 Period 对象
period1 = pd.Period("2020-09-23")
period2 = pd.Period(freq="D", year = 2021, month = 7, day = 16, hour = 2,minute = 35)
# 显示 Period 对象
print("Period1...\n", period1)
print("Period2...\n", period2)
# 获取日期从两个 Period 对象中返回一年中的第几天
res1 = period1.dayofyear
res2 = period2.dayofyear
# 从两个 Period 对象中返回一年中的第几天
# 返回值范围为 1 到 365(普通年份)和 1 到 366(闰年)
print("\n从第一个 Period 对象中返回的一年中的第几天...\n", res1)
print("\n从第二个 Period 对象中返回的一年中的第几天...\n", res2)
输出
将产生以下代码 −
Period1... 2020-09-23 Period2... 2021-07-16 从第一个 Period 对象中返回的一年中的第几天... 267 从第二个 Period 对象中返回的一年中的第几天... 197
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

