开发者

Formatting timedelta object python

I wrote this little script to format a timedelta object according to my needs:

   def due_format(self):
        time_diff = abs((self.due - datetime.datetime.now()).total_seconds())
        days = time_diff / 60 / 60 / 24
        hours = time_diff / 60 / 60
        minutes = time_diff / 60
        hours_wo_days = hours - (math.floor(days) * 24)
        minutes_wo_hours = minutes -开发者_开发知识库 (math.floor(hours) * 60)
        if (days >= 7):
            self.due_format = '{} Days'.format(int(days))
        elif (hours > 48):
            self.due_format = '{} Days, {} Hours'.format(int(days), int(hours_wo_days))
        elif (hours <= 48 and hours >= 10 ):
            self.due_format = '{} Hours'.format(int(hours))
        elif (hours <= 1):
            self.due_format = '{} Minutes'.format(int(minutes))
        elif (hours < 10):
            self.due_format = '{} Hours, {:.0f} Minutes'.format(int(hours), int(minutes_wo_hours))

I'm getting the feeling that my approach makes things overly complicated and wanted to ask you guys if you would've attacked this problem differently. Are there any shortcuts that I could take advantage of? I hope this question is appropriate for SO.


timedelta instance have attributes .days and .seconds which save a few lines. They also keep the values small, so you can convert to int once early instead of for each string format. This also removes the need for abs() and .floor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜