Convert a timedelta to days, hours and minutes

穿精又带淫゛_ 提交于 2019-11-26 05:57:22

问题


I\'ve got a timedelta. I want the days, hours and minutes from that - either as a tuple or a dictionary... I\'m not fussed.

I must have done this a dozen times in a dozen languages over the years but Python usually has a simple answer to everything so I thought I\'d ask here before busting out some nauseatingly simple (yet verbose) mathematics.

Mr Fooz raises a good point.

I\'m dealing with \"listings\" (a bit like ebay listings) where each one has a duration. I\'m trying to find the time left by doing when_added + duration - now

Am I right in saying that wouldn\'t account for DST? If not, what\'s the simplest way to add/subtract an hour?


回答1:


If you have a datetime.timedelta value td, td.days already gives you the "days" you want. timedelta values keep fraction-of-day as seconds (not directly hours or minutes) so you'll indeed have to perform "nauseatingly simple mathematics", e.g.:

def days_hours_minutes(td):
    return td.days, td.seconds//3600, (td.seconds//60)%60



回答2:


This is a bit more compact, you get the hours, minutes and seconds in two lines.

days = td.days
hours, remainder = divmod(td.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
# If you want to take into account fractions of a second
seconds += td.microseconds / 1e6



回答3:


days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60

As for DST, I think the best thing is to convert both datetime objects to seconds. This way the system calculates DST for you.

>>> m13 = datetime(2010, 3, 13, 8, 0, 0)  # 2010 March 13 8:00 AM
>>> m14 = datetime(2010, 3, 14, 8, 0, 0)  # DST starts on this day, in my time zone
>>> mktime(m14.timetuple()) - mktime(m13.timetuple())     # difference in seconds
82800.0
>>> _/3600                                                # convert to hours
23.0



回答4:


I don't understand

days, hours, minutes = td.days, td.seconds // 3600, td.seconds // 60 % 60

how about this

days, hours, minutes = td.days, td.seconds // 3600, td.seconds % 3600 / 60.0

You get minutes and seconds of a minute as a float.




回答5:


timedeltas have a days and seconds attribute .. you can convert them yourself with ease.



来源:https://stackoverflow.com/questions/2119472/convert-a-timedelta-to-days-hours-and-minutes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!