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
- Rounding down (flooring): toward negative infinity. Set every unit smaller than the target to zero.
- Rounding up (ceiling): toward positive infinity. Add enough time to reach the next boundary.
- 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.
| Function | Description | Example |
round_datetime_nearest | Rounds time to the nearest specified unit. | round_datetime_nearest(dt, 60)
(Round to Nearest Minute) |
floor_datetime | Floors time to the specified unit. | floor_datetime(dt, 3600)
(Floor to Hour) |
ceil_datetime | Ceils time to the specified unit. | ceil_datetime(dt, 3600)
(Ceil to Hour) |
pytz and dateutil | Used for managing time zones. | dt.astimezone(pytz.UTC) |
Rounding timezone-aware datetimes
Time zones add complexity. Libraries like pytz or dateutil manage them:
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.
Related reading
- rreplace - How to replace the last occurrence of an expression in a string?
- Run a Python script from another Python script, passing in arguments
- Run celery task without workers
- Run Class methods in threads python
- Run inference using Onnx model in python?
- Run localhost server in Google Colab notebook
- Run manage.py from AWS EB Linux instance
- Run py.test test in different process
System design interview problems on this topic
- Design a Web Crawler: solution and walkthrough
- Design a Task Scheduler: solution and walkthrough
- Design a URL Shortener (TinyURL): solution and walkthrough
- Design an API Rate Limiter: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo 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 courseData 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.