Skip to chapter content
navan✳THE BUILD LABPYTHON / GUIDE
0/26 read
CHAPTER 19 / 26 · TIME AND MEDIA

Time, scheduling, and processes.

Represent instants accurately and decide what should happen when a task runs later.

BY NAVAN SAMI5 MIN READTHEORY FIRST
01 / THE BASICS

Start here.

A program may need to record when something happened, wait for a later moment, or start another process. A date describes a calendar day; a time describes a clock reading; a datetime combines them. A duration is different: it measures how long an interval lasts. Python's datetime module represents these ideas with distinct types so adding a duration to a date is clearer than treating everything as a string.

Time zones give a clock reading its context. The same instant can be morning in one place and evening in another. A naive datetime has no timezone attached and can be ambiguous when shared or scheduled. An aware datetime includes timezone information. For elapsed time inside one running program, a monotonic clock is safer than a wall clock because the wall clock can be adjusted while the program runs.

Scheduling means arranging for work to begin later, but a sleeping script is not a complete scheduler. A long-running job may stop when a machine restarts, and a task can fail after it begins. A system scheduler can launch a command at chosen times, while the Python program itself should be able to explain success and failure. subprocess starts another program; its arguments, exit status, and output must be handled as carefully as any other external boundary.

02 / THE IDEA

Build the model.

A clock time is not quite the same as an instant. 09:00 in Dubai and 09:00 in London describe different instants, and a local clock can jump when daylight-saving rules change. Use timezone-aware datetime values for events shared across locations, store a stable timezone such as UTC for comparison, and convert to a person's local zone for display.

Scheduling also changes the shape of a program. When a job runs unattended, nobody is watching the terminal. It must know where to find its inputs, how to log a failure, and whether repeating the job would duplicate an action. A schedule is only a trigger; reliability comes from the behavior of the task it triggers.

03 / UNDER THE SURFACE

How it works.

datetime handles calendar dates and wall-clock times. timedelta represents a duration; adding one day to a timezone-aware value is not always identical to adding 24 hours across a clock change. time.monotonic() is better for measuring elapsed time because it keeps increasing even if the system clock is corrected. time.sleep pauses a process, but a long-running sleeping loop is usually less robust than an operating-system scheduler.

Use cron, Task Scheduler, or a job service to start a script at a chosen time. Give the script an absolute or configured working directory, bounded runtime, and clear exit status. Make repeated execution safe when possible: write a report to a dated path, or check whether a record has already been processed before sending it again.

subprocess.run starts another program with an argument list and waits for it. Passing a list avoids a shell interpreting special characters. Set check=True so a nonzero exit status becomes an exception, and use a timeout for commands that may hang. Capture output when your program needs to inspect it, and never assemble a shell command from untrusted input.

04 / A WORKED EXAMPLE

Read it line by line.

example.py
from datetime import datetime, timezone, timedelta
now = datetime.now(timezone.utc)
deadline = now + timedelta(days=7)
print(deadline.isoformat())

datetime.now(timezone.utc) creates an aware instant. timedelta adds seven 24-hour days, and isoformat produces a text representation that includes the UTC offset. The exact output depends on when the script runs. For a local appointment, use a named time zone and define how ambiguous clock times should be handled.

05 / ANOTHER EXAMPLE

See the rule again.

example-2.py
import time
start = time.monotonic()
total = sum(range(100_000))
elapsed = time.monotonic() - start
print(total, elapsed >= 0)

The sum is 4,999,950,000 and the second printed value is True. monotonic measures elapsed duration; it is not a date and should not be stored as a timestamp.

06 / REMEMBER THIS

A mistake to avoid.

A script scheduled for 09:00 can run twice, late, or not at all after a machine restart or clock change. Design the task to detect duplicate work and record its outcome.

Finished this chapter?
Built with curiosity. By Navan Sami. ↗Python · Understand the idea, then write the code.