Python Pandas – 将给定的Timestamp转换为Period

Python Pandas – 将给定的Timestamp转换为Period

要将给定的Timestamp转换为Period,请使用 timestamp.to_period() 方法。在其中使用 freq 参数设置频率。

首先,导入所需的库−

import pandas as pd

在Pandas中设置Timestamp对象

timestamp = pd.Timestamp('2021-09-14T15:12:34.261811624')

现在将Timestamp转换为Period。我们使用值为’M’的”freq”参数将频率设置为月份。

timestamp.to_period(freq='M')

示例

以下是代码

import pandas as pd

# 在Pandas中设置Timestamp对象
timestamp = pd.Timestamp('2021-09-14T15:12:34.261811624')

# 显示Timestamp
print("Timestamp...\n", timestamp)

# 将Timestamp转换为Period
# 我们使用值为'M'的"freq"参数将频率设置为月份。
print("\nTimestamp to Period...\n", timestamp.to_period(freq='M'))

输出

这将产生以下代码

Timestamp...
 2021-09-14 15:12:34.261811624

Timestamp to Period...
2021-09

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程