user13226257
user13226257

Reputation:

Python datetime module and timedelta methods

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.

Upvotes: 0

Views: 357

Answers (3)

Serge Ballesta
Serge Ballesta

Reputation: 148900

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...

Upvotes: 0

Raman
Raman

Reputation: 39

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

Upvotes: 0

Albert Nguyen
Albert Nguyen

Reputation: 377

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'>

Upvotes: 1

Related Questions