Python Pandas - 格式化并返回 Period 对象的字符串表示形式
pythonserver side programmingprogramming更新于 2026/1/25 12:28:17
要格式化并返回 Period 对象的字符串表示形式,请使用 period.strftime() 方法。使用该方法,将格式说明符设置为参数,如 strftime('%d-%b-%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 representative (format)...\n", period.strftime('%d-%b-%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 representative (format)...\n", period.strftime('%d-%b-%Y'))
# 显示结果
print("\nString representation (format with different directives)...\n",
period.strftime('%b. %d, %Y was a %A'))
输出
这将生成以下代码
Period... 2021-09-18 08:20:45 String representation (format)... 18-Sep-2021 String representation (format with different directives)... Sep. 18, 2021 was a Saturday
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

