如何在Python中将datetime.timedelta转换为分钟,小时?

时间:2013-01-07 04:48:07

标签: python django

我得到一个这样的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小时

10 个答案:

答案 0 :(得分:85)

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)

答案 1 :(得分:16)

datetime.timedelta对应于两个日期之间的差异,而不是日期本身。它仅以天,秒和微秒表示,因为较大的时间单位(如月和年)不能干净地分解(30天1个月或0.9677个月?)。

如果您想将timedelta转换为小时和分钟,可以使用total_seconds()方法获取总秒数,然后进行一些数学计算:

x = datetime.timedelta(1, 5, 41038)  # Interval of 1 day and 5.41038 seconds
secs = x.total_seconds()
hours = int(secs / 3600)
minutes = int(secs / 60) % 60

答案 2 :(得分:6)

如果我们只需要打印[D day[s], ][H]H:MM:SS[.UUUUUU]形式的字符串,就不需要自定义帮助函数。 timedelta对象支持执行此操作的str()操作。它甚至可以在Python 2.6中使用。

>>> from datetime import timedelta
>>> timedelta(seconds=90136)
datetime.timedelta(1, 3736)
>>> str(timedelta(seconds=90136))
'1 day, 1:02:16'

答案 3 :(得分:2)

只需使用strftime:)

类似的东西:

my_date = datetime.datetime(2013, 1, 7, 10, 31, 34, 243366, tzinfo=<UTC>)
print(my_date.strftime("%Y, %d %B"))

将问题编辑为格式timedelta后,您可以使用:

def timedelta_tuple(timedelta_object):
   return timedelta_object.days, timedelta_object.seconds//3600, (timedelta_object.seconds//60)%60

答案 4 :(得分:1)

我定义了自己的帮助函数,将timedelta对象转换为'HH:MM:SS'格式 - 只有小时,分钟和秒,而不会将小时数改为几天。

def format_timedelta(td):
    hours, remainder = divmod(td.total_seconds(), 3600)
    minutes, seconds = divmod(remainder, 60)
    hours, minutes, seconds = int(hours), int(minutes), int(seconds)
    if hours < 10:
        hours = '0%s' % int(hours)
    if minutes < 10:
        minutes = '0%s' % minutes
    if seconds < 10:
        seconds = '0%s' % seconds
    return '%s:%s:%s' % (hours, minutes, seconds)

答案 5 :(得分:1)

from nsepy import get_history
from datetime import date

dfc=get_history(symbol="HDFCBANK",start=date(2015,5,12),end=date(2020,5,18))
# Try this code
from datetime import timedelta

class TimeDelta(timedelta):
    def __str__(self):
        _times = super(TimeDelta, self).__str__().split(':')
        if "," in _times[0]:
            _hour = int(_times[0].split(',')[-1].strip())
            if _hour:
                _times[0] += " hours" if _hour > 1 else " hour"
            else:
                _times[0] = _times[0].split(',')[0]
        else:
            _hour = int(_times[0].strip())
            if _hour:
                _times[0] += " hours" if _hour > 1 else " hour"
            else:
                _times[0] = ""
        _min = int(_times[1])
        if _min:
            _times[1] += " minutes" if _min > 1 else " minute"
        else:
            _times[1] = ""
        _sec = int(_times[2])
        if _sec:
            _times[2] += " seconds" if _sec > 1 else " second"
        else:
            _times[2] = ""
        return ", ".join([i for i in _times if i]).strip(" ,").title()

答案 6 :(得分:0)

您要以该格式打印日期吗?这是Python文档:http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

>>> a = datetime.datetime(2013, 1, 7, 10, 31, 34, 243366)
>>> print a.strftime('%Y %d %B, %M:%S%p')
>>> 2013 07 January, 31:34AM

对于timedelta:

>>> a =  datetime.timedelta(0,5,41038)
>>> print '%s seconds, %s microseconds' % (a.seconds, a.microseconds)

但请注意,您应该确保它具有相关价值。对于上述情况,它没有小时和分钟值,您应该从秒计算。

答案 7 :(得分:0)

我不认为自己是个好主意。

如果只需要漂亮的输出,只需使用str函数将其隐藏到str()中,或直接对其进行print()隐藏即可。

如果进一步使用小时和分钟,则可以使用datetime将其解析为datetime.strptime()对象(并用datetime.time()方法提取时间部分),例如:< / p>

import datetime

delta = datetime.timedelta(seconds=10000)
time_obj = datetime.datetime.strptime(str(delta),'%H:%M:%S').time()

答案 8 :(得分:0)

此(较旧的)问题的另一种替代方法:

import datetime
import pytz
import time

pacific=pytz.timezone('US/Pacific')
now=datetime.datetime.now()
# pacific.dst(now).total_seconds() yields 3600 secs. [aka 1 hour]
time.strftime("%-H", time.gmtime(pacific.dst(now).total_seconds()))
'1'

以上是判断当前时区是否实际处于夏令时的好方法。 (它提供0或1的偏移量。)无论如何,实际工作是由time.strftime("%H:%M:%S", time.gmtime(36901))完成的,它确实对gmtime()的输出起作用。

>>> time.strftime("%H:%M:%S",time.gmtime(36901))  # secs = 36901
'10:15:01'

就这样! (注意:这是link to format specifiers for time.strftime()。...)

答案 9 :(得分:-2)

datetime.timedelta(hours=1, minutes=10)
#python 2.7