TimedRotatingFileHandler rotates Python log files according to time instead of file size. It belongs to logging.handlers and is useful when an application should start a new log every hour, day, midnight, or selected weekday while retaining only a chosen number of older files. This lesson continues directly from OSPython.028: Python Logging Basics, OSPython.029: Logging to Files with FileHandler, and OSPython.030: Rotating Log Files with RotatingFileHandler.
Time-Based Rotation vs. Size-Based Rotation
Python’s logging.handlers documentation separates the two rotating handlers clearly: RotatingFileHandler rolls over when a file approaches maxBytes, while TimedRotatingFileHandler rolls over according to a time schedule. Use size-based rotation when disk-file size is the main limit; use time-based rotation when operators want predictable periods such as one log per day or one log per hour.

Build a Daily TimedRotatingFileHandler
The handler needs a filename plus its rotation schedule. In this example, when="midnight" requests daily rollover at midnight, interval=1 means every one interval, backupCount=7 keeps at most seven older rotated files, and encoding="utf-8" gives the file an explicit text encoding. The logger still needs a level, formatter, and attached handler exactly like the earlier logging lessons.
import logging
from logging.handlers import TimedRotatingFileHandler
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
handler = TimedRotatingFileHandler(
"app.log",
when="midnight",
interval=1,
backupCount=7,
encoding="utf-8",
)
formatter = logging.Formatter(
"%(asctime)s %(levelname)s %(name)s: %(message)s"
)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.info("Application started")
Understand when, interval, backupCount, utc, and atTime
The when value can represent seconds (S), minutes (M), hours (H), days (D), weekdays (W0 through W6), or midnight. Python calculates rollover from when × interval; weekday rotation ignores the numeric interval for choosing the weekday. By default times are local, while utc=True switches rollover calculations to UTC. For midnight or weekday schedules, atTime can supply a specific datetime.time. With nonzero backupCount, Python deletes the oldest rotated files when the retained count is exceeded.
Rollover Happens When a Log Record Is Emitted
A critical troubleshooting detail is that TimedRotatingFileHandler does not wake up on its own like a separate scheduler. Python’s documentation states that subsequent rollover calculation occurs when rollover happens, and rollover itself happens only while the handler is emitting output. A program configured for one-minute rotation but producing messages only every five minutes can therefore show gaps between rotated filenames. This also explains why a short script launched periodically by systemd timers or cron-style automation may behave differently from a continuously running service.
Basic Troubleshooting
If rotation does not occur, first confirm that the program is still running and actually emits a log record after the scheduled rollover time. Then check write/rename permissions, verify that only the intended process owns the file, inspect when, interval, utc, and atTime, and remember that changing the configured interval can leave older files behind because retention deletion depends on the interval and sortable date/time suffixes. Keep custom namer functions simple and preserve sortable time information if backupCount should reliably remove the oldest files.
Exercise
- Create a logger with
TimedRotatingFileHandler. - Set
when="S",interval=10, andbackupCount=3for a quick lab. - Write one INFO message every two seconds for about one minute.
- Inspect the directory and identify the active log plus the timestamped backups.
- Change
utc=Trueand repeat the test. - Return the handler to a practical production interval after the lab.
Knowledge Check + Answers
- What makes TimedRotatingFileHandler different from RotatingFileHandler? It rotates according to time rather than a maximum file size.
- What does
when="midnight"mean? The handler schedules rollover around midnight, or aroundatTimewhen that option is supplied. - What does
backupCount=7do? It keeps at most seven older rotated files under the handler’s normal retention rules. - What does
utc=Truechange? Rollover calculations use UTC rather than local time. - Does the handler rotate if the application produces no new log records? Not at the scheduled instant by itself; rollover is checked when output is emitted.
- Why should timestamp suffixes remain sortable? TimedRotatingFileHandler uses the dated filenames when deciding which old backups to delete.
Prior Python Lessons
- OSPython.028: Python Logging Basics
- OSPython.029: Logging to Files with FileHandler
- OSPython.030: Rotating Log Files with RotatingFileHandler
Editor’s Note
Featured image: realistic code photograph via Unsplash, cropped to exactly 1200×630. Body image: separate realistic code-editor photograph via Unsplash. Primary technical reference: current Python logging.handlers documentation. Every YouTube video in this lesson is distinct; the Reddit embed is directly about TimedRotatingFileHandler time-based rollover behavior.
Support and donation options are available through BitcoinVersus.Tech.
BitcoinVersus.Tech is not a financial advisor. Content is provided for informational and educational purposes.

Leave a comment