Python Pandas - Convert given Timestamp to Period with hourly frequency

PythonServer Side ProgrammingProgramming

To convert given Timestamp to Period, use the timestamp.to_period() method. Within that, set the frequency using the freq parameter. For hourly frequency, set freq as H.

At first, import the required libraries −

import pandas as pd

Create the timestamp object in Pandas

timestamp = pd.Timestamp(2021, 9, 18, 11, 50, 20, 33)

Convert timestamp to Period. We have set the frequency as hourly using the "freq" parameter with value 'H'

timestamp.to_period(freq='H')

Example

Following is the code

import pandas as pd

# set the timestamp object in Pandas
timestamp = pd.Timestamp(2021, 9, 18, 11, 50, 20, 33)

# display the Timestamp
print("Timestamp...\n", timestamp)

# convert timestamp to Period
# we have set the frequency as hourly using the "freq" parameter with value 'H'
print("\nTimestamp to Period with hourly frequency...\n", timestamp.to_period(freq='H'))

Output

This will produce the following code

Timestamp...
 2021-09-18 11:50:20.000033
Timestamp to Period with hourly frequency...
 2021-09-18 11:00
raja
Updated on 13-Oct-2021 07:02:33

Advertisements