3 回答
TA贡献1836条经验 获得超5个赞
您只需使用str()将timeDelta转换为字符串即可。下面是一个例子:
import datetime
start = datetime.datetime(2009,2,10,14,00)
end = datetime.datetime(2009,2,10,16,00)
delta = end-start
print(str(delta))
# prints 2:00:00
TA贡献2051条经验 获得超10个赞
如您所知,您可以通过访问.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
TA贡献1836条经验 获得超13个赞
>>> str(datetime.timedelta(hours=10.56))10:33:36>>> td = datetime.timedelta(hours=10.505) # any timedelta object>>> ':'.join(str(td).split(':')[:2])10:30
timedelta
str()
print td
添加回答
举报