Python Pandas - 将周期对象作为具有月频的时间戳返回


若要将周期对象作为具有月频的时间戳返回,请使用 period.to_timestamp() 方法,并将 freq 参数设为“M”。

首先,导入所需的库 −

import pandas as pd

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

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

显示 Period 对象

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

返回 Period 对象的时间戳表示。我们已通过使用“freq”参数设置频率。频率设置为“M”,即每月

print("\nPeriod to Timestamp with monthly (month-end) frequency...\n",
period.to_timestamp(freq='M'))

示例

以下是代码

import pandas as pd

# The pandas.Period represents a period of time
# Creating a Period object
period = pd.Period(freq="S", year = 2021, month = 9, day = 18, hour = 17, minute = 20, second = 45)

# display the Period object
print("Period...\n", period)

# Return the Timestamp representation of the Period object
# We have set the frequency using the "freq" parameter
# The frequency is set as 'M' i.e. monthly
print("\nPeriod to Timestamp with monthly (month-end) frequency...\n", period.to_timestamp(freq='M'))

输出

这将生成以下代码

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

Period to Timestamp with monthly (month-end) frequency...
2021-09-30 00:00:00

更新于:2021 年 10 月 20 日

236 次浏览

开启你的 事业

完成课程即可获得认证

立即开始
广告