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

