如何在Python中将datetime.timedelta转换为分钟,小时?
发布于2019-08-26 13:15
我得到一个这样的start_date:
from django.utils.timezone import utc import datetime start_date = datetime.datetime.utcnow().replace(tzinfo=utc) end_date = datetime.datetime.utcnow().replace(tzinfo=utc) duration = end_date - start_date
我得到这样的输出:
datetime.timedelta(0, 5, 41038)
如何将此转换为正常时间,如下所示?
这样10分钟,1小时
解决方案
没有内置的timedelta
对象格式化程序,但它很容易自己做:
days, seconds = duration.days, duration.seconds hours = days * 24 + seconds // 3600 minutes = (seconds % 3600) // 60 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 // 3600 minutes = (seconds % 3600) // 60 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 // (3600 * 24) hours = (seconds // 3600) % 24 minutes = (seconds // 60) % 60 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)
赞 (0)