DateTime
rounding
programming
Python
timestamps

How to round a Python datetime (nearest, floor, ceiling)

Codemia Knowledge Hub ·

To round a Python datetime, take the seconds elapsed in the day, round that number to a multiple of your unit (60 for a minute, 3600 for an hour), and add the difference back with a timedelta while dropping the microseconds. The same idea gives you floor, ceiling, or nearest rounding.

Rounding is useful for logging events at consistent intervals, reducing data size, and normalizing timestamps so they compare cleanly. Datetimes are often precise to microseconds, and most applications do not need that.

Three kinds of rounding

  1. Rounding down (flooring): toward negative infinity. Set every unit smaller than the target to zero.
  2. Rounding up (ceiling): toward positive infinity. Add enough time to reach the next boundary.
  3. Rounding to nearest: compare the previous and next boundaries and pick the closer one.

Floor, ceiling and nearest functions in Python

Each function takes round_to in seconds.

python
1from datetime import datetime, timedelta
2import pytz
3
4def round_datetime_nearest(dt, round_to):
5    seconds = (dt.replace(tzinfo=None) - dt.min).seconds
6    rounding = (seconds + round_to // 2) // round_to * round_to
7    return dt + timedelta(0, rounding - seconds, -dt.microsecond)
8
9def floor_datetime(dt, round_to):
10    seconds = (dt.replace(tzinfo=None) - dt.min).seconds
11    rounding = seconds // round_to * round_to
12    return dt + timedelta(0, rounding - seconds, -dt.microsecond)
13
14def ceil_datetime(dt, round_to):
15    seconds = (dt.replace(tzinfo=None) - dt.min).seconds
16    rounding = (seconds + round_to - 1) // round_to * round_to
17    return dt + timedelta(0, rounding - seconds, -dt.microsecond)
18
19# Example usage
20dt = datetime(2023, 10, 21, 13, 34, 50, 600000)
21print("Original: ", dt)
22print("Rounded to Nearest Minute: ", round_datetime_nearest(dt, 60))
23print("Floored to Hour: ", floor_datetime(dt, 3600))
24print("Ceiled to Hour: ", ceil_datetime(dt, 3600))
FunctionDescriptionExample
round_datetime_nearestRounds time to the nearest specified unit.round_datetime_nearest(dt, 60) (Round to Nearest Minute)
floor_datetimeFloors time to the specified unit.floor_datetime(dt, 3600) (Floor to Hour)
ceil_datetimeCeils time to the specified unit.ceil_datetime(dt, 3600) (Ceil to Hour)
pytz and dateutilUsed for managing time zones.dt.astimezone(pytz.UTC)

Rounding timezone-aware datetimes

Time zones add complexity. Libraries like pytz or dateutil manage them:

python
1# Timezone-aware DateTime rounding
2dt = datetime(2023, 10, 21, 13, 34, 50, 600000, tzinfo=pytz.UTC)
3local_tz = pytz.timezone('America/New_York')
4dt_local = dt.astimezone(local_tz)
5rounded_dt = floor_datetime(dt_local, 3600)
6print("Rounded Local Time: ", rounded_dt)

Daylight saving time changes can also affect rounding of aware datetimes. Use timezone-aware objects and adjust the logic if an operation spans a DST change.

Performance and cross-system consistency

Rounding a large number of records can become a bottleneck; use batch processing and optimized libraries for big datasets. Datetime behavior can also differ across operating systems and databases, so configure environments consistently and use compatible libraries.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms