我在格式化日期时间时遇到了麻烦。timedelta对象。
这就是我想做的: 我有一个对象列表,对象类的成员之一是显示事件持续时间的timedelta对象。我想以小时:分钟的格式显示这个持续时间。
我尝试了各种方法来做这件事,但我有困难。我目前的方法是为返回小时和分钟的对象在类中添加方法。我可以通过除以time得到小时数。秒乘以3600,四舍五入。我在得到剩余的秒并将其转换为分钟时遇到了麻烦。
顺便说一下,我使用谷歌AppEngine和Django模板来表示。
我在格式化日期时间时遇到了麻烦。timedelta对象。
这就是我想做的: 我有一个对象列表,对象类的成员之一是显示事件持续时间的timedelta对象。我想以小时:分钟的格式显示这个持续时间。
我尝试了各种方法来做这件事,但我有困难。我目前的方法是为返回小时和分钟的对象在类中添加方法。我可以通过除以time得到小时数。秒乘以3600,四舍五入。我在得到剩余的秒并将其转换为分钟时遇到了麻烦。
顺便说一下,我使用谷歌AppEngine和Django模板来表示。
当前回答
# Format seconds to days, hours, minutes and seconds string
def ptime(seconds):
if(seconds >= 86400):
d = seconds // 86400 # // floor division
return (f"{round(d)}d") + ptime(seconds - d * 86400)
else:
if(seconds >= 3600):
h = seconds // 3600
return (f"{round(h)}h") + ptime(seconds - h * 3600)
else:
if(seconds >= 60):
m = seconds // 60
return(f"{round(m)}m" + ptime(seconds - m * 60))
else:
if (seconds > 0):
return(f"{round(seconds)}s")
else:
return("")
其他回答
# Format seconds to days, hours, minutes and seconds string
def ptime(seconds):
if(seconds >= 86400):
d = seconds // 86400 # // floor division
return (f"{round(d)}d") + ptime(seconds - d * 86400)
else:
if(seconds >= 3600):
h = seconds // 3600
return (f"{round(h)}h") + ptime(seconds - h * 3600)
else:
if(seconds >= 60):
m = seconds // 60
return(f"{round(m)}m" + ptime(seconds - m * 60))
else:
if (seconds > 0):
return(f"{round(seconds)}s")
else:
return("")
他已经有一个timedelta对象,所以为什么不使用其内置方法total_seconds()将其转换为秒,然后使用divmod()获得小时和分钟?
hours, remainder = divmod(myTimeDelta.total_seconds(), 3600)
minutes, seconds = divmod(remainder, 60)
# Formatted only for hours and minutes as requested
print '%s:%s' % (hours, minutes)
无论时间增量是天还是年,这都是有效的。
我的datetime。Timedelta对象的时间大于一天。这是一个更深层次的问题。以上所有讨论都假设时间不超过一天。timedelta实际上是一个由日、秒和微秒组成的元组。上面的讨论应该使用td。秒,因为乔做了,但如果你有天,它不包括在秒值。
我得到2个日期时间和打印天和小时之间的时间跨度。
span = currentdt - previousdt
print '%d,%d\n' % (span.days,span.seconds/3600)
def td_format(td_object):
seconds = int(td_object.total_seconds())
periods = [
('year', 60*60*24*365),
('month', 60*60*24*30),
('day', 60*60*24),
('hour', 60*60),
('minute', 60),
('second', 1)
]
strings=[]
for period_name, period_seconds in periods:
if seconds > period_seconds:
period_value , seconds = divmod(seconds, period_seconds)
has_s = 's' if period_value > 1 else ''
strings.append("%s %s%s" % (period_value, period_name, has_s))
return ", ".join(strings)
如您所知,您可以通过访问.seconds属性从timedelta对象中获得total_seconds。
Python提供了内置函数divmod(),它允许:
s = 13420
hours, remainder = divmod(s, 3600)
minutes, seconds = divmod(remainder, 60)
print('{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds)))
# result: 03:43:40
或者你可以结合使用模和减法来转换小时和余数:
# arbitrary number of seconds
s = 13420
# hours
hours = s // 3600
# remaining seconds
s = s - (hours * 3600)
# minutes
minutes = s // 60
# remaining seconds
seconds = s - (minutes * 60)
# total time
print('{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds)))
# result: 03:43:40