虽然timedelta
对象没有内置的格式化程序,但自己编写格式化程序非常容易:
days, seconds = duration.days, duration.seconds
hours = days * 24 + seconds
minutes = (seconds % 3600)
seconds = seconds % 60
或者等价地,如果您使用的是 Python 2.7+ 或 3.2+ 版本:
seconds = duration.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60
现在你可以按照自己的需求打印它:
'{} minutes, {} hours'.format(minutes, hours)
例如:
def convert_timedelta(duration):
days, seconds = duration.days, duration.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds % 3600) // 60
seconds = (seconds % 60)
return hours, minutes, seconds
td = datetime.timedelta(2, 7743, 12345)
hours, minutes, seconds = convert_timedelta(td)
print '{} minutes, {} hours'.format(minutes, hours)
这将打印:
9 minutes, 50 hours
如果您想要获得“10分钟,1小时”而不是“10分钟,1个小时”,那么您也需要手动进行更改:
print '{} minute{}, {} hour{}'.format(minutes, 's' if minutes != 1 else '',
hours, 's' if minutes != 1 else '')
或者你可能想编写一个english_plural
函数来代替重复自己的's'
,而不是手动添加。
从您的评论中可以看出,您实际上希望保持每天分开。这更容易:
def convert_timedelta(duration):
days, seconds = duration.days, duration.seconds
hours = seconds
minutes = (seconds % 3600)
seconds = (seconds % 60)
return days, hours, minutes, seconds
如果您想将此转换为单个值以存储在数据库中,然后将该单个值转换回格式,请执行以下操作:
def dhms_to_seconds(days, hours, minutes, seconds):
return (((days * 24) + hours) * 60 + minutes) * 60 + seconds
def seconds_to_dhms(seconds):
days = seconds
hours = (seconds
minutes = (seconds
seconds = seconds % 60
return days, hours, minutes, seconds
因此,将其综合起来:
def store_timedelta_in_database(thingy, duration):
seconds = dhms_to_seconds(*convert_timedelta(duration))
db.execute('INSERT INTO foo (thingy, duration) VALUES (?, ?)',
thingy, seconds)
db.commit()
def print_timedelta_from_database(thingy):
cur = db.execute('SELECT duration FROM foo WHERE thingy = ?', thingy)
seconds = int(cur.fetchone()[0])
days, hours, minutes, seconds = seconds_to_dhms(seconds)
print '{} took {} minutes, {} hours, {} days'.format(thingy, minutes, hours, days)