将timedelta格式化为字符串 [英] Format timedelta to string

查看:481
本文介绍了将timedelta格式化为字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法格式化datetime.timedelta对象.

这就是我想要做的: 我有一个对象列表,该对象类的成员之一是一个timedelta对象,它显示事件的持续时间.我想以小时:分钟的格式显示该持续时间.

Here's what I'm trying to do: I have a list of objects and one of the members of the class of the object is a timedelta object that shows the duration of an event. I would like to display that duration in the format of hours:minutes.

我尝试了多种方法来执行此操作,但遇到了困难.我当前的方法是为我的对象添加类的方法,这些方法返回小时和分钟.我可以通过将timedelta.seconds除以3600并四舍五入来获得小时数.我在获取剩余秒数并将其转换为分钟时遇到麻烦.

I have tried a variety of methods for doing this and I'm having difficulty. My current approach is to add methods to the class for my objects that return hours and minutes. I can get the hours by dividing the timedelta.seconds by 3600 and rounding it. I'm having trouble with getting the remainder seconds and converting that to minutes.

顺便说一句,我正在使用带有Django模板的Google AppEngine进行演示.

By the way, I'm using Google AppEngine with Django Templates for presentation.

推荐答案

感谢大家的帮助.我采纳了您的许多想法并将它们组合在一起,让我知道您的想法.

Thanks everyone for your help. I took many of your ideas and put them together, let me know what you think.

我向此类添加了两个方法:

I added two methods to the class like this:

def hours(self):
    retval = ""
    if self.totalTime:
        hoursfloat = self.totalTime.seconds / 3600
        retval = round(hoursfloat)
    return retval

def minutes(self):
    retval = ""
    if self.totalTime:
        minutesfloat = self.totalTime.seconds / 60
        hoursAsMinutes = self.hours() * 60
        retval = round(minutesfloat - hoursAsMinutes)
    return retval

在我的django中,我使用了这个(总和是对象,它在字典中):

In my django I used this (sum is the object and it is in a dictionary):

<td>{{ sum.0 }}</td>    
<td>{{ sum.1.hours|stringformat:"d" }}:{{ sum.1.minutes|stringformat:"#02.0d" }}</td>

这篇关于将timedelta格式化为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆