Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python timedelta seconds vs total_seconds

Looking at the datetime docs, I can't seem to get the difference between the attribute seconds and the method total_seconds() used on a timedelta object. Is it just precision? That the former is an int and the latter a float? Or am I missing something?

like image 424
toringe Avatar asked Aug 02 '18 11:08

toringe


People also ask

How do I convert Timedelta to seconds in Python?

Use the total_seconds() method of a timedelta object to get the number of seconds since the epoch. Use the timestamp() method. If your Python version is greater than 3.3 then another way is to use the timestamp() method of a datetime class to convert datetime to seconds.

What is total_seconds?

The total_seconds() function is used to return the total number of seconds covered for the specified duration of time instance. This function is used in the timedelta class of module DateTime. Syntax: total_seconds()

What does Timedelta mean in Python?

Timedelta in Python is an object that represents the duration. It is mainly used to calculate the duration between two dates and times. It is also used for retrieving the object with some delta date and time.


2 Answers

seconds is the number of seconds within a day, which is in [0, 86399]. total_seconds is the entire timedelta converted to seconds, and can be any value, for example 604800.0 for one week, or 0.1 for 100 milliseconds.

like image 187
John Zwinck Avatar answered Oct 01 '22 21:10

John Zwinck


You can construct a timedelta from days, seconds, microseconds, milliseconds, minutes, hours and weeks. Please note the order of these parameters, which is absolutely not useful and probably caused historically.

Internally, the timedelta structure is only made up of days, seconds and microseconds. And these are the properties you can access once the timedelta has been built. Even if you used hours, minutes etc. to construct the object, that information is gone.

import datetime

t = datetime.timedelta(hours=2, minutes=30)
print(t.seconds)

If seconds become larger than 86400 (24*60*60), they will overflow into one day:

import datetime

t = datetime.timedelta(hours=24, minutes=1)
print(t.seconds)
print(t.days)

And thus, timespan.seconds is quite a useless property, because it's only a part of the truth and meaningless without the other two components. The same applies for timespan.days and timespan.microseconds. They should really have been made internal and thus adhere to the principle of information hiding.

total_seconds() on the other hand side, is a valid representation of the timespan. It considers all 3 properties combined into a single number.

like image 34
Thomas Weller Avatar answered Oct 01 '22 22:10

Thomas Weller