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

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

问题描述

我在格式化 datetime.timedelta 对象时遇到问题.

I'm having trouble formatting a datetime.timedelta object.

这是我想要做的:我有一个对象列表,该对象类的一个成员是一个 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.

顺便说一下,我使用 Google AppEngine 和 Django 模板进行演示.

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 中,我使用了这个(sum 是对象,它在字典中):

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天全站免登陆