Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Pandas - How to perform ceil operation on the DateTimeIndex with milliseconds frequency
To perform a ceil operation on the DateTimeIndex with milliseconds frequency, use the DateTimeIndex.ceil() method. For milliseconds frequency, use the freq parameter with value 'ms'.
What is the Ceil Operation?
The ceil operation rounds timestamps up to the nearest specified frequency. For milliseconds, it rounds up to the next millisecond boundary, removing microseconds and nanoseconds precision.
Syntax
DateTimeIndex.ceil(freq)
Parameters
-
freq ? The frequency to round up to. Use
'ms'for milliseconds
Example
Let's create a DateTimeIndex with microsecond precision and apply the ceil operation ?
import pandas as pd
# Create DatetimeIndex with period 5 and frequency as 40 seconds
# The timezone is Australia/Adelaide
datetimeindex = pd.date_range('2021-10-18 07:20:32.261811624', periods=5,
tz='Australia/Adelaide', freq='40S')
# Display DateTimeIndex
print("DateTimeIndex...")
print(datetimeindex)
# Display DateTimeIndex frequency
print("\nDateTimeIndex frequency...")
print(datetimeindex.freq)
# Perform ceil operation with milliseconds frequency
print("\nPerforming ceil operation with milliseconds frequency...")
result = datetimeindex.ceil(freq='ms')
print(result)
DateTimeIndex...
DatetimeIndex(['2021-10-18 07:20:32.261811624+10:30',
'2021-10-18 07:21:12.261811624+10:30',
'2021-10-18 07:21:52.261811624+10:30',
'2021-10-18 07:22:32.261811624+10:30',
'2021-10-18 07:23:12.261811624+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq='40S')
DateTimeIndex frequency...
<40 * Seconds>
Performing ceil operation with milliseconds frequency...
DatetimeIndex(['2021-10-18 07:20:32.262000+10:30',
'2021-10-18 07:21:12.262000+10:30',
'2021-10-18 07:21:52.262000+10:30',
'2021-10-18 07:22:32.262000+10:30',
'2021-10-18 07:23:12.262000+10:30'],
dtype='datetime64[ns, Australia/Adelaide]', freq=None)
How It Works
Notice how the original timestamps had microseconds precision (.261811624), but after the ceil operation with 'ms' frequency, they were rounded up to the next millisecond (.262000). The microseconds and nanoseconds were removed.
Key Points
- The
ceil()method always rounds up to the next boundary - Using
freq='ms'rounds to millisecond precision - The operation preserves timezone information
- The resulting DateTimeIndex loses its original frequency
Conclusion
The DateTimeIndex.ceil() method with freq='ms' efficiently rounds timestamps up to millisecond precision. This is useful for data alignment and reducing timestamp precision in time series analysis.
