Python Pandas - 将给定的时间戳转换为具有月频率的周期
pythonserver side programmingprogramming更新于 2025/12/28 5:32:17
要将给定的时间戳转换为周期,请使用 timestamp.to_period() 方法。在其中,使用 freq 参数设置频率。对于月频率,将 freq 设置为 M。
首先,导入所需的库 −
import pandas as pd
在 Pandas 中设置时间戳对象
timestamp = pd.Timestamp(2021, 9, 18, 11, 50, 20, 33)
将时间戳转换为周期。我们使用值为"M"的"freq" 参数将频率设置为每月。
timestamp.to_period(freq='M')
示例
以下是代码
import pandas as pd
# 在 Pandas 中设置时间戳对象
timestamp = pd.Timestamp(2021, 9, 18, 11, 50, 20, 33)
# 显示时间戳
print("时间戳...\n", timestamp)
# 将时间戳转换为周期
# 我们使用值为"freq" 参数将频率设置为每月。值为 'M' 的参数
print("\n时间戳到每月频率的周期...\n", timestamp.to_period(freq='M'))
输出
这将生成以下代码
时间戳... 2021-09-18 11:50:20.000033 时间戳到每月频率的周期... 2021-09
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

