Python Pandas - How to perform ceil operation on the DateTimeIndex with hourly frequency


To perform ceil operation on the DateTimeIndex with hourly frequency, use the DateTimeIndex.ceil() method. For hourly frequency, use the freq parameter with value ‘H’.

At first, import the required libraries −

import pandas as pd

Create a DatetimeIndex with period 5 and frequency as min i.e. minutes −

datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='20min')

Performing Ceil operation on DateTimeIndex date with hourly frequency. For hourly frequency, we have used 'H' −

print("\nPerforming ceil operation with hourly frequency...\n",
datetimeindex.ceil(freq='H'))

Example

Following is the code −

import pandas as pd

# DatetimeIndex with period 5 and frequency as min i.e. minutes
# timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-09-29 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='20min')

# display DateTimeIndex
print("DateTimeIndex...\n", datetimeindex)

# display DateTimeIndex frequency
print("DateTimeIndex frequency...\n", datetimeindex.freq)

# Ceil operation on DateTimeIndex date with hourly frequency
# For hourly frequency, we have used 'H'
print("\nPerforming ceil operation with hourly frequency...\n",
datetimeindex.ceil(freq='H'))

Output

This will produce the following code −

DateTimeIndex...
DatetimeIndex(['2021-09-29 07:20:32.261811624+09:30',
'2021-09-29 07:40:32.261811624+09:30',
'2021-09-29 08:00:32.261811624+09:30',
'2021-09-29 08:20:32.261811624+09:30',
'2021-09-29 08:40:32.261811624+09:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='20T')
DateTimeIndex frequency...
<20 * Minutes>

Performing ceil operation with hourly frequency...
DatetimeIndex(['2021-09-29 08:00:00+09:30', '2021-09-29 08:00:00+09:30',
'2021-09-29 09:00:00+09:30', '2021-09-29 09:00:00+09:30',
'2021-09-29 09:00:00+09:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)

Updated on: 19-Oct-2021

90 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements