Python Pandas - 格式化 Period 对象并显示不带世纪的年份

pythonserver side programmingprogramming更新于 2026/1/25 13:32:17

要格式化 Period 对象,请使用 period.strftime() 方法;要显示不带世纪的年份,请将参数设置为 %y。

首先,导入所需的库 −

import pandas as pd

pandas.Period 表示一段时间。创建一个 Period 对象

period = pd.Period(freq="S", year = 2021, month = 9, day = 18, hour = 8,minute = 20, second = 45)

显示 Period 对象

print("Period...\n", period)

显示结果。这里显示的是年份,没有世纪

print("\nString 表示(年份没有世纪)...\n", period.strftime('%y'))

示例

以下是代码


import pandas as pd

# pandas.Period 表示一段时期
# 创建 Period 对象
period = pd.Period(freq="S", year = 2021, month = 9, day = 18, hour = 8,minute = 20,second = 45)

# 显示 Period 对象
print("Period...\n", period)

# 显示结果
# 这里,显示年份而不显示世纪
print("\nString representation (year without century)...\n", period.strftime('%y'))

输出

这将生成以下代码

Period...
2021-09-18 08:20:45

String representation (year without century)...
21

相关文章


有用资源