Python格式的timedelta到字符串 [英] Python format timedelta to string

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

问题描述

我是一个Python新手(2周),我无法格式化一个 datetime.timedelta 对象。

I'm a Python newbie (2 weeks) and 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.

如果有人可以帮助或知道更好的解决方法

If anyone can help or knows of a better way to resolve this, I would be very happy.

谢谢,

推荐答案

感谢大家的帮助。我把很多想法放在一起,让我知道你的想法。

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>

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

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