Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

datetime.timedelta

Represents an elapsed duration and normalizes its days, seconds and microseconds fields.

Version: Python 3.14; repository image, production runtime not attested

Syntax

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

Represents an elapsed duration and normalizes its days, seconds and microseconds fields.

The seconds field excludes whole days. Use the total duration when interpreting a negative interval.

A duration aggregates the supplied units and normalizes them into days, seconds within a day and microseconds within a second. Only days can be negative after normalization. An interval of −1 second has fields −1 day and 86399 seconds. total_seconds() reports the complete interval as -1.0, whereas seconds gives only the remainder. Combined fractional microseconds round to the nearest integer, ties to even: 0.5 and 1.5 microseconds become 0 and 2. The normalized days field must be between -999999999 and 999999999 inclusive, otherwise OverflowError is raised.

from datetime import timedelta
d = timedelta(microseconds=-1)
assert (d.days, d.seconds, d.microseconds) == (-1, 86399, 999999)
assert d == timedelta(days=-1, microseconds=86_399_999_999)
assert timedelta(hours=36).total_seconds() == 129600.0
assert [timedelta(microseconds=n).microseconds for n in [0.5, 1.5]] == [0, 2]
assert timedelta.min.days == -999999999 and timedelta.max.days == 999999999
try:
    timedelta(days=1000000000)
except OverflowError:
    pass
else:
    raise AssertionError

Examples

import datetime
d = datetime.timedelta(seconds=-1)
print(d.days, d.seconds)
print(d.total_seconds())

Result

-1 86399
-1.0

A duration aggregates the supplied units and normalizes them into days, seconds within a day and microseconds within a second. Only days can be negative after normalization. An interval of −1 second has fields −1 day and 86399 seconds. total_seconds() reports the complete interval as -1.0, whereas seconds gives only the remainder. Combined fractional microseconds round to the nearest integer, ties to even: 0.5 and 1.5 microseconds become 0 and 2. The normalized days field must be between -999999999 and 999999999 inclusive, otherwise OverflowError is raised.

Sources