On Fri, 15 Apr 2022 at 00:54, Loris Bennett <loris.benn...@fu-berlin.de> wrote: > > Hi, > > With Python 3.9.2 I get > > $ import datetime > $ s = "1-00:01:01" > $ t = datetime.datetime.strptime(s, "%d-%H:%M:%S") > $ d = datetime.timedelta(days=t.day, hours=t.hour, minutes=t.minute, > seconds=t.second) > $ d.days > 1 > $ d.seconds > 61 > $ d.minutes > AttributeError: 'datetime.timedelta' object has no attribute 'minutes' > > Is there a particular reason why there are no attributes 'minutes' and > 'hours and the attribute 'seconds' encompasses is the entire fractional > day? >
You can get those by dividing: >>> divmod(d, datetime.timedelta(minutes=1)) (1441, datetime.timedelta(seconds=1)) But the obvious question is: how many minutes ARE there in this time period? I give a response of 1441 (or if you prefer, 1441 + 1/60 or roughly 1441.017), but you might just as reasonably consider that there is one minute. If a good definition could be chosen, it wouldn't be too hard to add a bunch of properties to the timedelta that let you view it in other ways. Otherwise, the easiest way is probably to define yourself a set of units and sequentially divmod: >>> units = {"days": datetime.timedelta(days=1), "hours": >>> datetime.timedelta(hours=1), "minutes": datetime.timedelta(minutes=1), >>> "seconds": datetime.timedelta(seconds=1)} >>> for label, unit in units.items(): ... n, d = divmod(d, unit) ... print(n, label) ... 1 days 0 hours 1 minutes 1 seconds >>> This way, you have full control over which units are "interesting"; for instance, the constructor supports weeks, but a lot of applications won't consider them to be important, and would prefer to see "20 days" than "2 weeks and 6 days". But, as mentioned, adding properties to timedelta would be a relatively benign change, so it could be done if there's enough need and a good definition. ChrisA -- https://mail.python.org/mailman/listinfo/python-list