ZetCode

Python time module

last modified November 19, 2026 Python 3.15

In this article we give an overview of the time module in Python. Each function is covered in more detail in its own article; the links are in the Python time API section of the index.

The time module

The time module is a thin layer over the C library time functions of the platform. It works with two representations of time: a number of seconds since the epoch, and a struct_time tuple with the year, month, day, and other fields. It also provides clocks for measuring elapsed time and the sleep function.

The epoch is the moment from which time is counted. On all platforms Python supports it is 1970-01-01 00:00:00 UTC, the Unix epoch. The seconds since the epoch do not count leap seconds.

For date arithmetic, aware time zones, and dates outside the range of the C library, use the datetime and zoneinfo modules instead. The examples in this article run with the TZ environment variable set to Europe/Bratislava, so local time is CET or CEST.

Current time

The time.time function returns the current time as seconds since the epoch, a float. The time.ctime function returns the current local time as a string.

current_time.py
import time

print(time.time())
print(time.time_ns())
print(time.ctime())

The time_ns function returns the same moment as an integer number of nanoseconds. A number of seconds like this is called a timestamp or Unix time. The output differs on every run.

$ python current_time.py
1795094804.8022225
1795094804802231797
Thu Nov 19 14:26:44 2026

The struct_time tuple

Functions such as gmtime and localtime convert a timestamp to a time.struct_time. It is a named tuple, so its fields are accessible by name and by index.

struct_time_fields.py
import time

t = time.gmtime(0)
print(t)

print(t.tm_year, t.tm_mon, t.tm_mday)
print(t[0], t[1], t[2])
print(t.tm_wday, t.tm_yday)
print(t.tm_zone, t.tm_gmtoff)

year, month, day, *rest = t
print(year, month, day, rest)

The gmtime(0) call returns the epoch itself. The table lists the nine fields. In addition, tm_zone holds the time zone abbreviation and tm_gmtoff the offset from UTC in seconds; they are attributes only and are not part of the tuple, so unpacking gives nine values.

IndexAttributeValues
0tm_yearfor example 2026
1tm_mon1 to 12
2tm_mday1 to 31
3tm_hour0 to 23
4tm_min0 to 59
5tm_sec0 to 61 (60 for leap seconds, 61 for historical reasons)
6tm_wday0 to 6, Monday is 0
7tm_yday1 to 366
8tm_isdst1 if daylight saving time applies, 0 if not, -1 if unknown

January 1, 1970 was a Thursday, so tm_wday is 3.

$ python struct_time_fields.py
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
1970 1 1
1970 1 1
3 1
GMT 0
1970 1 1 [0, 0, 0, 3, 1, 0]

Local time and UTC

The gmtime function converts a timestamp to UTC; the localtime function converts it to the local time zone, which is taken from the TZ variable or the system settings.

local_utc.py
import time

summer = 1784104200
winter = 1768465800

for secs in (summer, winter):
    utc = time.gmtime(secs)
    loc = time.localtime(secs)
    print(f'UTC:   {utc.tm_hour:02}:{utc.tm_min:02} {utc.tm_zone}')
    print(f'local: {loc.tm_hour:02}:{loc.tm_min:02} {loc.tm_zone} '
          f'(offset {loc.tm_gmtoff // 3600:+} h, isdst={loc.tm_isdst})')

We convert two fixed timestamps, one in July and one in January, so the output is the same on every run. Both are 08:30 UTC. In Bratislava, the summer time (CEST) is two hours ahead of UTC and the winter time (CET) one hour; tm_isdst tells which applies. Called without an argument, both functions use the current time.

$ python local_utc.py
UTC:   08:30 GMT
local: 10:30 CEST (offset +2 h, isdst=1)
UTC:   08:30 GMT
local: 09:30 CET (offset +1 h, isdst=0)

Back to seconds

The time.mktime function converts a local struct_time back to a timestamp. Its UTC counterpart is not in the time module; it is calendar.timegm.

to_seconds.py
import calendar
import time

secs = 1784104200

loc = time.localtime(secs)
utc = time.gmtime(secs)

print(time.mktime(loc))
print(calendar.timegm(utc))

print(time.mktime(utc))
print(time.mktime(utc) - secs)

t = (2026, 12, 24, 18, 0, 0, 0, 0, -1)
print(time.ctime(time.mktime(t)))

Both round trips return the original timestamp; mktime returns a float. Passing a UTC tuple to mktime is a common bug: the function treats the fields as local time and the result is off by the UTC offset, one hour here. The last call builds a tuple by hand. Setting tm_isdst to -1 lets the C library decide whether daylight saving time applies; the weekday and day of the year are ignored, so zeros are fine.

$ python to_seconds.py
1784104200.0
1784104200
1784100600.0
-3600.0
Thu Dec 24 18:00:00 2026

Formatting time

The time.strftime function formats a struct_time according to a format string with % directives.

format_time.py
import time

t = time.localtime(1784104200)

print(time.strftime('%Y-%m-%d %H:%M:%S', t))
print(time.strftime('%d.%m.%Y', t))
print(time.strftime('%A, %B %d, %Y', t))
print(time.strftime('%a %b %d %I:%M %p', t))
print(time.strftime('%j %U %z %Z', t))
print(time.strftime('%c', t))
print(time.asctime(t))
print(time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(1784104200)))

%Y, %m, and %d are the year, month, and day, %H, %M, and %S the time. %A and %B are the full weekday and month names, %I and %p the 12-hour clock. %j is the day of the year, %U the week number, and %z and %Z the UTC offset and zone name. %c is the locale's preferred representation, which in the C locale matches asctime. The last line formats a UTC time in ISO 8601 with the Z suffix. The full list of directives is in the time.strftime article.

$ python format_time.py
2026-07-15 10:30:00
15.07.2026
Wednesday, July 15, 2026
Wed Jul 15 10:30 AM
196 28 +0200 CEST
Wed Jul 15 10:30:00 2026
Wed Jul 15 10:30:00 2026
2026-07-15T08:30:00Z

Parsing time

The time.strptime function parses a string according to a format and returns a struct_time.

parse_time.py
import time

t = time.strptime('2026-07-15 10:30', '%Y-%m-%d %H:%M')
print(t)
print(time.mktime(t))

t2 = time.strptime('15/Jul/2026:10:30:00 +0200', '%d/%b/%Y:%H:%M:%S %z')
print(t2.tm_gmtoff, t2.tm_zone)

for text in ('2026-02-30', '2026-7-15', '15.07.2026'):
    try:
        print(time.strptime(text, '%Y-%m-%d')[:3])
    except ValueError as e:
        print(f'{text}: {e}')

Fields missing from the format get default values, and tm_isdst is -1. The %z directive parses a UTC offset into tm_gmtoff; the zone name stays unknown. An invalid date or a string that does not match the format raises ValueError. Note that %m and %d also accept numbers without a leading zero, so 2026-7-15 is valid.

$ python parse_time.py
time.struct_time(tm_year=2026, tm_mon=7, tm_mday=15, tm_hour=10, tm_min=30, tm_sec=0, tm_wday=2, tm_yday=196, tm_isdst=-1)
1784104200.0
7200 None
2026-02-30: day 30 must be in range 1..28 for month 2 in year 2026
(2026, 7, 15)
15.07.2026: time data '15.07.2026' does not match format '%Y-%m-%d'

Time zone variables

The time module exposes the local time zone in a few variables. After the TZ environment variable is changed, the time.tzset function (Unix only) reinitializes them.

timezone_info.py
import os
import time

def show():
    print(f'{os.environ["TZ"]:22} tzname={time.tzname} '
          f'timezone={time.timezone} daylight={time.daylight}')

show()

for tz in ('UTC', 'America/New_York', 'Asia/Kolkata'):
    os.environ['TZ'] = tz
    time.tzset()
    show()
    print(' ', time.strftime('%H:%M %Z', time.localtime(1784104200)))

tzname holds the names of standard and daylight saving time, timezone is the offset of standard time west of UTC in seconds (so it is negative in Europe and Asia), and daylight is nonzero if the zone has daylight saving time at all. The same timestamp is shown in each zone. Changing TZ affects the whole process; to work with several zones at once, use zoneinfo.

$ python timezone_info.py
Europe/Bratislava      tzname=('CET', 'CEST') timezone=-3600 daylight=1
UTC                    tzname=('UTC', 'UTC') timezone=0 daylight=0
  08:30 UTC
America/New_York       tzname=('EST', 'EDT') timezone=18000 daylight=1
  04:30 EDT
Asia/Kolkata           tzname=('IST', 'IST') timezone=-19800 daylight=0
  14:00 IST

Sleeping

The time.sleep function suspends the calling thread for the given number of seconds. The argument may be a float.

sleeping.py
import time

for i in range(3):
    print(time.strftime('%H:%M:%S'), 'tick', i)
    time.sleep(1)

start = time.monotonic()
time.sleep(0.25)
print(f'slept {time.monotonic() - start:.3f} s')

The loop prints a line every second. Since Python 3.11, sleep uses a high-resolution timer on Linux, so a 0.25 second sleep takes about 0.25 seconds. It can last longer if the system is busy, but it is never shorter. In asyncio code, use asyncio.sleep instead, which does not block the event loop.

$ python sleeping.py
14:26:44 tick 0
14:26:45 tick 1
14:26:46 tick 2
slept 0.250 s

Clocks

Besides the wall clock of time.time, the module has several other clocks. The time.get_clock_info function describes them.

clocks.py
import time

names = ['time', 'monotonic', 'perf_counter', 'process_time', 'thread_time']

for name in names:
    info = time.get_clock_info(name)
    print(f'{name:13} {info.implementation:40} '
          f'monotonic={info.monotonic!s:5} adjustable={info.adjustable}')

print()
print(time.monotonic())
print(time.perf_counter())

The wall clock (CLOCK_REALTIME) is adjustable: NTP or the administrator can move it forward or back, so the difference of two time.time values may even be negative. The monotonic and perf_counter clocks never go backwards, which makes them right for timeouts and measuring durations. Their values have no fixed starting point (here it is the system uptime), so only differences are meaningful. process_time and thread_time count CPU time of the process or the current thread.

$ python clocks.py
time          clock_gettime(CLOCK_REALTIME)            monotonic=False adjustable=True
monotonic     clock_gettime(CLOCK_MONOTONIC)           monotonic=True  adjustable=False
perf_counter  clock_gettime(CLOCK_MONOTONIC)           monotonic=True  adjustable=False
process_time  clock_gettime(CLOCK_PROCESS_CPUTIME_ID)  monotonic=True  adjustable=False
thread_time   clock_gettime(CLOCK_THREAD_CPUTIME_ID)   monotonic=True  adjustable=False

16968.934767565
16968.934773617

Measuring elapsed time

The perf_counter clock measures wall time with the highest available resolution; process_time measures only the CPU time used by the process.

elapsed.py
import time

def work():
    return sum(i * i for i in range(3_000_000))

for job in (lambda: time.sleep(0.5), work):
    wall = time.perf_counter()
    cpu = time.process_time()
    job()
    wall = time.perf_counter() - wall
    cpu = time.process_time() - cpu
    print(f'wall {wall:.3f} s, cpu {cpu:.3f} s')

During sleep, the wall time passes but the process uses no CPU. The computation keeps the CPU busy, so both values are nearly equal. A big difference between wall and CPU time means the program waits for something, such as I/O or a lock. For benchmarks of small snippets, the timeit module repeats the code and is more reliable. The times vary from run to run.

$ python elapsed.py
wall 0.500 s, cpu 0.000 s
wall 0.153 s, cpu 0.153 s

Nanosecond functions

The _ns variants of the clock functions, such as time_ns and perf_counter_ns, return integer nanoseconds.

nanoseconds.py
import time

ns = time.time_ns()
secs = time.time()
print(ns)
print(f'{secs:.9f}')

big = 1_784_104_200_123_456_789
print(big / 1e9)
print(f'{big / 1e9:.9f}')
print(divmod(big, 10**9))

start = time.perf_counter_ns()
total = sum(range(1000))
print(time.perf_counter_ns() - start, 'ns')

A float has 53 bits of mantissa, so a current timestamp stored as float seconds is precise to only about a quarter of a microsecond. The fixed number big shows the loss: as a float the last nanosecond digits are wrong. The integer form keeps all digits, and divmod splits it into seconds and nanoseconds. The perf_counter_ns function is useful for timing very short operations.

$ python nanoseconds.py
1795094808837125649
1795094808.837128401
1784104200.1234567
1784104200.123456717
(1784104200, 123456789)
5399 ns

A drift-free ticker

The last program runs a task at a fixed interval. Sleeping for the interval after each task would make the period longer by the duration of the task. Instead, we compute the next start time on the monotonic clock and sleep only for the remaining time.

ticker.py
import time

def run_every(interval, count, task):
    """Call task every interval seconds without accumulating drift."""
    next_run = time.monotonic()

    for n in range(count):
        task(n)
        next_run += interval
        delay = next_run - time.monotonic()
        if delay > 0:
            time.sleep(delay)

def task(n):
    now = time.time()
    ms = int(now * 1000) % 1000
    stamp = time.strftime('%H:%M:%S', time.localtime(now))
    print(f'{stamp}.{ms:03} task {n}')
    time.sleep(0.12)  # simulated work

start = time.perf_counter()
run_every(0.5, 6, task)
print(f'total {time.perf_counter() - start:.2f} s')

The task takes 0.12 seconds, yet it starts every 0.5 seconds and the six runs take three seconds in total. Scheduling uses monotonic, because a change of the wall clock must not break the schedule, while the log line shows the wall time from time.time with milliseconds, which strftime cannot format by itself. The output differs on every run.

$ python ticker.py
14:26:48.847 task 0
14:26:49.348 task 1
14:26:49.848 task 2
14:26:50.347 task 3
14:26:50.847 task 4
14:26:51.347 task 5
total 3.00 s

Source

time – Time access and conversions

In this article we have worked with the time module in Python. See also Python datetime, Python format datetime, Python zoneinfo, and the articles on time.struct_time, time.perf_counter, and time.sleep.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.