datetime-truncate
raw JSON → 1.1.1 verified Mon Apr 27 auth: no python
Truncate datetime objects to a specified level of precision (e.g., year, month, day, hour, minute, second). Version 1.1.1 is stable with no active changes; the package is in maintenance mode.
pip install datetime-truncate Common errors
error ImportError: cannot import name 'truncate_to' from 'datetime_truncate' ↓
cause The function was renamed from truncate_to to truncate in version 1.1.0.
fix
Install latest version: pip install datetime-truncate --upgrade. Then use from datetime_truncate import truncate.
error AttributeError: 'datetime.datetime' object has no attribute 'truncate' ↓
cause datetime_truncate does not monkey-patch datetime; it provides a standalone function.
fix
Import and call truncate() from datetime_truncate, not as a method on a datetime object.
error ValueError: invalid level: 'weeks' ↓
cause The library does not support truncation to weeks; only year, month, day, hour, minute, second.
fix
Use 'day' or 'hour' and adjust manually.
Warnings
gotcha The function flips between truncate() and truncate_to(). In version 1.0.0, the function was named truncate_to; in 1.1.0 it was renamed to truncate. Check your version. ↓
fix If using 1.0.x, use truncate_to. For 1.1+, use truncate.
deprecated Level parameter uses singular names: 'year', 'month', 'day', 'hour', 'minute', 'second'. Not plural. ↓
fix Use 'hour' not 'hours'.
gotcha Time zones are not preserved; the function returns a naive datetime. If you pass a timezone-aware datetime, the tzinfo is lost. ↓
fix Manually re-attach timezone after truncation: result = truncate(dt, 'day').replace(tzinfo=dt.tzinfo).
Imports
- truncate wrong
from datetime import truncatecorrectfrom datetime_truncate import truncate
Quickstart
from datetime import datetime
from datetime_truncate import truncate
dt = datetime(2025, 4, 15, 10, 30, 45, 123456)
truncated = truncate(dt, 'hour')
print(truncated) # 2025-04-15 10:00:00