75

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

4

10 回答 10

153

对象没有内置的格式化程序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)
于 2013-01-07T05:02:08.740 回答
23

Adatetime.timedelta对应于两个日期之间的差异,而不是日期本身。它仅以天、秒和微秒表示,因为像月和年这样的较大时间单位不能完全分解(是 30 天 1 个月还是 0.9677 个月?)。

如果要将 a 转换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
于 2013-01-07T05:04:27.910 回答
20

如果我们只需要打印表单的字符串,则不需要自定义帮助函数[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'
于 2017-05-14T14:33:57.740 回答
7

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

如果您只想要一个漂亮的输出,只需将其转换strstr()函数或直接print()它。

如果还有小时和分钟的进一步使用,您可以将其解析为datetime对象使用datetime.strptime()(并使用 mehtod 提取时间部分datetime.time()),例如:

import datetime

delta = datetime.timedelta(seconds=10000)
time_obj = datetime.datetime.strptime(str(delta),'%H:%M:%S').time()
于 2019-02-16T08:59:58.600 回答
4

只需使用strftime :)

像这样的东西:

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

将您的问题编辑为 format 后timedelta,您可以使用:

def timedelta_tuple(timedelta_object):
   return timedelta_object.days, timedelta_object.seconds//3600, (timedelta_object.seconds//60)%60
于 2013-01-07T04:55:29.417 回答
3

我定义了自己的辅助函数来将 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)
于 2016-03-03T08:29:54.280 回答
2

这个(较旧的)问题的替代方法是从转换为秒的 timedelta 创建一个相对时间。这可以使用从epochtime.gmtime(...)接受秒数的方法来完成:

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

而且,就是这样!(注意:这是格式说明符的链接,time.strftime()因此可以根据需要将差异截断为任何单位。...)

值得注意的是,这种技术也是判断您当前时区是否实际上处于夏令时的好方法。(它提供了 0 或 1 小时的偏移量,这意味着它基本上可以解释为布尔值。)

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'

这可以呈现为一个方法is_standard_time(...),其中1意味着 true 和0意味着 false。

于 2019-10-08T02:42:36.977 回答
2
# 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()

# Test
>>> str(TimeDelta(seconds=10))
'10 Seconds'
>>> str(TimeDelta(seconds=60))
'01 Minute'
>>> str(TimeDelta(seconds=90))
'01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3000))
'50 Minutes'
>>> str(TimeDelta(seconds=3600))
'1 Hour'
>>> str(TimeDelta(seconds=3690))
'1 Hour, 01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3660))
'1 Hour, 01 Minute'
>>> str(TimeDelta(seconds=3630))
'1 Hour, 30 Seconds'
>>> str(TimeDelta(seconds=3600*20))
'20 Hours'
>>> str(TimeDelta(seconds=3600*20 + 3000))
'20 Hours, 50 Minutes'
>>> str(TimeDelta(seconds=3600*20 + 3630))
'21 Hours, 30 Seconds'
>>> str(TimeDelta(seconds=3600*20 + 3660))
'21 Hours, 01 Minute'
>>> str(TimeDelta(seconds=3600*20 + 3690))
'21 Hours, 01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3600*24))
'1 Day'
>>> str(TimeDelta(seconds=3600*24 + 10))
'1 Day, 10 Seconds'
>>> str(TimeDelta(seconds=3600*24 + 60))
'1 Day, 01 Minute'
>>> str(TimeDelta(seconds=3600*24 + 90))
'1 Day, 01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3600*24 + 3000))
'1 Day, 50 Minutes'
>>> str(TimeDelta(seconds=3600*24 + 3600))
'1 Day, 1 Hour'
>>> str(TimeDelta(seconds=3600*24 + 3630))
'1 Day, 1 Hour, 30 Seconds'
>>> str(TimeDelta(seconds=3600*24 + 3660))
'1 Day, 1 Hour, 01 Minute'
>>> str(TimeDelta(seconds=3600*24 + 3690))
'1 Day, 1 Hour, 01 Minute, 30 Seconds'
>>> str(TimeDelta(seconds=3600*24*2))
'2 Days'
>>> str(TimeDelta(seconds=3600*24*2 + 9999))
'2 Days, 2 Hours, 46 Minutes, 39 Seconds'
于 2020-05-19T04:54:20.537 回答
1

您想以该格式打印日期吗?这是 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

对于时间增量:

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

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

于 2013-01-07T04:55:19.160 回答
-1
datetime.timedelta(hours=1, minutes=10)
#python 2.7
于 2015-10-15T01:22:07.153 回答