'Python gives wrong result with .seconds attribute of timedelta data
>>>print(today - date, (today - date).seconds)
[1] 63 days, 8:45:34.250649 31534
↑
This is far away from the right result. 31534 seconds are much less than 63 days. Why is python giving the wrong value?
Solution 1:[1]
You are only requesting the seconds
of the timedelta
- you need the timedelta.total_seconds()
method.
The timedelta.seconds
attribute only reports the seconds from the last day of the delta.
https://docs.python.org/3/library/datetime.html#datetime.timedelta.total_seconds
import datetime
d1 = datetime.datetime.now()
d2 = datetime.datetime.now()-datetime.timedelta(days=1.4)
delta = d1-d2
print(delta, delta.seconds, delta.total_seconds(), sep="\n")
Output:
1 day, 9:35:59.999997
34559 # (9 * 60 + 35 ) * 60 + 59 ca. 34559 - the full day is not part of ".seconds"
120959.999997
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | alstr |