0
from datetime import datetime as dt


fmt = '%a %d %b %Y %H:%M:%S %z'
for i in range(int(input())):
    print(int(abs((dt.strptime(input(), fmt) - 
                   dt.strptime(input(), fmt)).total_seconds())))

Why are we able to call the total_seconds() method without importing the timedelta class? As total_seconds() is a method in timedelta class.

1
  • the module datetime imports it for its own use. you may import a module when you need o instanciate a class from it or call a static mehod from it Commented May 20, 2020 at 7:30

3 Answers 3

1

When you subtract 2 datetime objects, the result is timedelta object.

from datetime import datetime

dt1 = datetime.now()
dt2 = datetime.now()

value = dt2 - dt1

print(type(value))

Output is:

<class 'datetime.timedelta'>
Sign up to request clarification or add additional context in comments.

Comments

0

You are right, as you are subtracting two datetime objects. As per the method __sub__ it returns timedelta object (See below). And as you said total_seconds is method of timedelta class.

    def __sub__(self, other):
        "Subtract two datetimes, or a datetime and a timedelta."
        if not isinstance(other, datetime):
            if isinstance(other, timedelta):
                return self + -other
            return NotImplemented

        days1 = self.toordinal()
        days2 = other.toordinal()
        secs1 = self._second + self._minute * 60 + self._hour * 3600
        secs2 = other._second + other._minute * 60 + other._hour * 3600
        base = timedelta(days1 - days2,
                         secs1 - secs2,
                         self._microsecond - other._microsecond)
        if self._tzinfo is other._tzinfo:
            return base
        myoff = self.utcoffset()
        otoff = other.utcoffset()
        if myoff == otoff:
            return base
        if myoff is None or otoff is None:
            raise TypeError("cannot mix naive and timezone-aware time")
        return base + otoff - myoff

Comments

0

The import machinery works at 2 levels. First it loads and execute the module. So if it contains other imports, they are loaded (and executed) too. That means that the instruction

from datetime import datetime as dt

actually loads datetime (to be able to access datetime.datetime), and datetime.datetime. Because of that, datetime.timedelta is loaded too. In fact, it is required from datetime.datetime to be able to define the difference between 2 datetime.datetime objects. So everything has been loaded by the Python interpretor.

The second level imports symbols in the current namespace. At this level,

from datetime import datetime as dt

only creates the dt symbol in the namespace. That means that if you use directly datetime in your code, you will get a NameError because the symbol is undefined, but if you examine sys.module, you will find that it is there...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.