我得到这样的开始日期:
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对象的内置格式化程序,但是您自己可以很容易地做到这一点:
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'为您完成这些操作,而不是重复自己。
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)