如何在Python中将datetime.timedelta转换为分钟和小时? [英] How do I convert datetime.timedelta to minutes, hours in Python?

查看:606
本文介绍了如何在Python中将datetime.timedelta转换为分钟和小时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到这样的开始日期:

I get a start_date like this:

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)

如何我如何将其转换为如下所示的正常时间?

How do I convert this into normal time like the following?

10分钟,像这样的1小时

10 minutes, 1 hour like this

推荐答案

timedelta 对象没有内置的格式化程序,但是您自己做起来很容易:

There's no built-in formatter for timedelta objects, but it's pretty easy to do it yourself:

days, seconds = duration.days, duration.seconds
hours = days * 24 + seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60

或者,如果您在Python 2.7+或3.2 +:

Or, equivalently, if you're in Python 2.7+ or 3.2+:

seconds = duration.total_seconds()
hours = seconds // 3600
minutes = (seconds % 3600) // 60
seconds = seconds % 60

现在您可以按需要打印它:

Now you can print it however you want:

'{} 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个小时,您也需要手动进行操作:

If you want to get "10 minutes, 1 hour" instead of "10 minutes, 1 hours", you need to do that manually too:

print '{} minute{}, {} hour{}'.format(minutes, 's' if minutes != 1 else '',
                                      hours, 's' if minutes != 1 else '')

或者您可能想写一个 english_plural 函数为您执行的'位,而不是重复自己。

Or you may want to write an english_plural function to do the 's' bits for you, instead of repeating yourself.

从您的评论看来,您实际上是想让日子分开。甚至更容易:

From your comments, it sounds like you actually want to keep the days separate. That's even easier:

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

如果要将其转换为单个值以存储在数据库中,请将该单个值转换回格式化,请执行以下操作:

If you want to convert this to a single value to store in a database, then convert that single value back to format it, do this:

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)

这篇关于如何在Python中将datetime.timedelta转换为分钟和小时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆