Skip to content

datetime.timedelta returns unexpected value when passed a bool True for days arg #124852

@danish-wani

Description

@danish-wani

Bug report

Bug description:

Today I stumbled upon a strange issue where I was supposed to pass an integer value to datetime.timedelta for days arg but I was passing a boolean True value to this function as a positional argument. Below is what I was doing;

import datetime

datetime.datetime.now() -  datetime.timedelta(True)

# instead of

start_datetimestamp = datetime.datetime.now() -  datetime.timedelta(10)

to my surprise, when I checked the value start_datetimestamp it was not what I expected. Upon debugging it further I realized I was passing the boolean True instead of integer 10 as a positional argument to this function.

Since in my case, the days arg was initialized as True the below statement evaluated to True + 0 = 1, hence assigning 1 to days instead of raising a ValueError.

days += weeks*7 => True += 0 *7 => 1

image

Proposed better handling of this behaviour:

Adding a type check on all the arguments should possibly avoid this unexpected behaviour;

        d = s = us = 0
        assert isinstance(days, (int, float))
        assert isinstance(seconds, (int, float))
        assert isinstance(microseconds, (int, float))
        assert isinstance(milliseconds, (int, float))
        assert isinstance(minutes, (int, float))
        assert isinstance(hours, (int, float))
        assert isinstance(weeks, (int, float))

When a bool True is passed to datetime.timedelta

import datetime

datetime.timedelta(True)

# output
# datetime.timedelta(days=1)

CPython versions tested on:

3.10

Operating systems tested on:

macOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions