Reputation: 3
from datetime import datetime, timedelta
now = datetime.now()
then = datetime(2001, 1, 1)
delta = now-then
print(delta)
print(delta.days, delta.seconds)
print(delta.hours, delta.minutes)
gives the following errors:
6959 days, 16:09:27.863408
6959 58167
AttributeError: 'datetime.timedelta' object has no attribute 'hours'
AttributeError: 'datetime.timedelta' object has no attribute 'minutes'
is it a bug or a feature?
Upvotes: 0
Views: 225
Reputation: 40884
A feature: timedelta
objects only have .days
, .seconds
, and .microseconds
.
I suppose this is because days are sometimes irregular (e.g. due to leap seconds, and date arithmetic can account for that), while minutes and hours can be readily computed from seconds. Could have been slightly nicer, but still would have a few corner cases.
Upvotes: 1
Reputation: 532
You can check all attributes in this way:
>>> dir(delta)
['__abs__', '__add__', '__bool__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__pos__', '__radd__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rmod__', '__rmul__', '__rsub__', '__rtruediv__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', 'days', 'max', 'microseconds', 'min', 'resolution', 'seconds', 'total_seconds']
There are no "hours" and "minutes"
Upvotes: 0