如何将秒转换为小时,分钟和秒?

问题:如何将秒转换为小时,分钟和秒?

我有一个以秒为单位返回信息的函数,但是我需要以小时:分钟:秒存储该信息。

有没有简单的方法可以在Python中将秒转换为这种格式?

I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds.

Is there an easy way to convert the seconds to this format in Python?


回答 0

您可以使用datetime.timedelta功能:

>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'

You can use datetime.timedelta function:

>>> import datetime
>>> str(datetime.timedelta(seconds=666))
'0:11:06'

回答 1

通过使用divmod()仅执行一个除法运算就可以得到商和余数的函数,您只需执行两个数学运算就可以很快得出结果:

m, s = divmod(seconds, 60)
h, m = divmod(m, 60)

然后使用字符串格式将结果转换为所需的输出:

print('{:d}:{:02d}:{:02d}'.format(h, m, s)) # Python 3
print(f'{h:d}:{m:02d}:{s:02d}') # Python 3.6+

By using the divmod() function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations:

m, s = divmod(seconds, 60)
h, m = divmod(m, 60)

And then use string formatting to convert the result into your desired output:

print('{:d}:{:02d}:{:02d}'.format(h, m, s)) # Python 3
print(f'{h:d}:{m:02d}:{s:02d}') # Python 3.6+

回答 2

我很难说出这种简单的方法(至少我不记得语法),但是可以使用time.strftime,它提供了对格式的更多控制:

from time import strftime
from time import gmtime

strftime("%H:%M:%S", gmtime(666))
'00:11:06'

strftime("%H:%M:%S", gmtime(60*60*24))
'00:00:00'

gmtime用于将秒转换为所需的特殊元组格式strftime()

注意:在23:59:59之后截断

I can hardly name that an easy way (at least I can’t remember the syntax), but it is possible to use time.strftime, which gives more control over formatting:

from time import strftime
from time import gmtime

strftime("%H:%M:%S", gmtime(666))
'00:11:06'

strftime("%H:%M:%S", gmtime(60*60*24))
'00:00:00'

gmtime is used to convert seconds to special tuple format that strftime() requires.

Note: Truncates after 23:59:59


回答 3

使用datetime

使用':0>8'格式:

from datetime import timedelta

"{:0>8}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'

"{:0>8}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'

"{:0>8}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'

没有':0>8'格式:

"{}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'

"{}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'

"{}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'

使用time

from time import gmtime
from time import strftime

# NOTE: The following resets if it goes over 23:59:59!

strftime("%H:%M:%S", gmtime(125))
# Result: '00:02:05'

strftime("%H:%M:%S", gmtime(60*60*24-1))
# Result: '23:59:59'

strftime("%H:%M:%S", gmtime(60*60*24))
# Result: '00:00:00'

strftime("%H:%M:%S", gmtime(666777))
# Result: '17:12:57'
# Wrong

Using datetime:

With the ':0>8' format:

from datetime import timedelta

"{:0>8}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'

"{:0>8}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'

"{:0>8}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'

Without the ':0>8' format:

"{}".format(str(timedelta(seconds=66)))
# Result: '00:01:06'

"{}".format(str(timedelta(seconds=666777)))
# Result: '7 days, 17:12:57'

"{}".format(str(timedelta(seconds=60*60*49+109)))
# Result: '2 days, 1:01:49'

Using time:

from time import gmtime
from time import strftime

# NOTE: The following resets if it goes over 23:59:59!

strftime("%H:%M:%S", gmtime(125))
# Result: '00:02:05'

strftime("%H:%M:%S", gmtime(60*60*24-1))
# Result: '23:59:59'

strftime("%H:%M:%S", gmtime(60*60*24))
# Result: '00:00:00'

strftime("%H:%M:%S", gmtime(666777))
# Result: '17:12:57'
# Wrong

回答 4

这是我的快速技巧:

from humanfriendly import format_timespan
secondsPassed = 1302
format_timespan(secondsPassed)
# '21 minutes and 42 seconds'

有关更多信息,请访问:https : //humanfriendly.readthedocs.io/en/latest/#humanfriendly.format_timespan

This is my quick trick:

from humanfriendly import format_timespan
secondsPassed = 1302
format_timespan(secondsPassed)
# '21 minutes and 42 seconds'

For more info Visit: https://humanfriendly.readthedocs.io/en/latest/#humanfriendly.format_timespan


回答 5

如果您需要获取datetime.time价值,可以使用以下技巧:

my_time = (datetime(1970,1,1) + timedelta(seconds=my_seconds)).time()

您不能添加timedeltatime,但可以将其添加到datetime

UPD:同一技术的另一种变化:

my_time = (datetime.fromordinal(1) + timedelta(seconds=my_seconds)).time()

而不是1可以使用大于0的任何数字。在这里,我们使用这样的事实,即datetime.fromordinal始终返回组件为零的datetime对象time

If you need to get datetime.time value, you can use this trick:

my_time = (datetime(1970,1,1) + timedelta(seconds=my_seconds)).time()

You cannot add timedelta to time, but can add it to datetime.

UPD: Yet another variation of the same technique:

my_time = (datetime.fromordinal(1) + timedelta(seconds=my_seconds)).time()

Instead of 1 you can use any number greater than 0. Here we use the fact that datetime.fromordinal will always return datetime object with time component being zero.


回答 6

这就是我的方法。

def sec2time(sec, n_msec=3):
    ''' Convert seconds to 'D days, HH:MM:SS.FFF' '''
    if hasattr(sec,'__len__'):
        return [sec2time(s) for s in sec]
    m, s = divmod(sec, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    if n_msec > 0:
        pattern = '%%02d:%%02d:%%0%d.%df' % (n_msec+3, n_msec)
    else:
        pattern = r'%02d:%02d:%02d'
    if d == 0:
        return pattern % (h, m, s)
    return ('%d days, ' + pattern) % (d, h, m, s)

一些例子:

$ sec2time(10, 3)
Out: '00:00:10.000'

$ sec2time(1234567.8910, 0)
Out: '14 days, 06:56:07'

$ sec2time(1234567.8910, 4)
Out: '14 days, 06:56:07.8910'

$ sec2time([12, 345678.9], 3)
Out: ['00:00:12.000', '4 days, 00:01:18.900']

This is how I got it.

def sec2time(sec, n_msec=3):
    ''' Convert seconds to 'D days, HH:MM:SS.FFF' '''
    if hasattr(sec,'__len__'):
        return [sec2time(s) for s in sec]
    m, s = divmod(sec, 60)
    h, m = divmod(m, 60)
    d, h = divmod(h, 24)
    if n_msec > 0:
        pattern = '%%02d:%%02d:%%0%d.%df' % (n_msec+3, n_msec)
    else:
        pattern = r'%02d:%02d:%02d'
    if d == 0:
        return pattern % (h, m, s)
    return ('%d days, ' + pattern) % (d, h, m, s)

Some examples:

$ sec2time(10, 3)
Out: '00:00:10.000'

$ sec2time(1234567.8910, 0)
Out: '14 days, 06:56:07'

$ sec2time(1234567.8910, 4)
Out: '14 days, 06:56:07.8910'

$ sec2time([12, 345678.9], 3)
Out: ['00:00:12.000', '4 days, 00:01:18.900']

回答 7

以下设置对我有用。

def sec_to_hours(seconds):
    a=str(seconds//3600)
    b=str((seconds%3600)//60)
    c=str((seconds%3600)%60)
    d=["{} hours {} mins {} seconds".format(a, b, c)]
    return d


print(sec_to_hours(10000))
# ['2 hours 46 mins 40 seconds']

print(sec_to_hours(60*60*24+105))
# ['24 hours 1 mins 45 seconds']

The following set worked for me.

def sec_to_hours(seconds):
    a=str(seconds//3600)
    b=str((seconds%3600)//60)
    c=str((seconds%3600)%60)
    d=["{} hours {} mins {} seconds".format(a, b, c)]
    return d


print(sec_to_hours(10000))
# ['2 hours 46 mins 40 seconds']

print(sec_to_hours(60*60*24+105))
# ['24 hours 1 mins 45 seconds']

回答 8

dateutil.relativedelta如果您还需要访问浮点数的小时,分​​钟和秒,则非常方便。datetime.timedelta没有提供类似的界面。

from dateutil.relativedelta import relativedelta
rt = relativedelta(seconds=5440)
print(rt.seconds)
print('{:02d}:{:02d}:{:02d}'.format(
    int(rt.hours), int(rt.minutes), int(rt.seconds)))

版画

40.0
01:30:40

dateutil.relativedelta is convenient if you need to access hours, minutes and seconds as floats as well. datetime.timedelta does not provide a similar interface.

from dateutil.relativedelta import relativedelta
rt = relativedelta(seconds=5440)
print(rt.seconds)
print('{:02d}:{:02d}:{:02d}'.format(
    int(rt.hours), int(rt.minutes), int(rt.seconds)))

Prints

40.0
01:30:40

回答 9

小时(h)由楼层的秒数(//)除以3600(60分钟/小时* 60秒/分钟)

分钟(m),以剩余秒数(小时计算的剩余百分比,%)除以60(60秒/分钟)计算得出

类似地,以小时和分钟的余数计算秒数。

其余只是字符串格式!

def hms(seconds):
    h = seconds // 3600
    m = seconds % 3600 // 60
    s = seconds % 3600 % 60
    return '{:02d}:{:02d}:{:02d}'.format(h, m, s)

print(hms(7500))  # Should print 02h05m00s

hours (h) calculated by floor division (by //) of seconds by 3600 (60 min/hr * 60 sec/min)

minutes (m) calculated by floor division of remaining seconds (remainder from hour calculation, by %) by 60 (60 sec/min)

similarly, seconds (s) by remainder of hour and minutes calculation.

Rest is just string formatting!

def hms(seconds):
    h = seconds // 3600
    m = seconds % 3600 // 60
    s = seconds % 3600 % 60
    return '{:02d}:{:02d}:{:02d}'.format(h, m, s)

print(hms(7500))  # Should print 02h05m00s

回答 10

您可以将秒除以60得到分钟

import time
seconds = time.time()
minutes = seconds / 60
print(minutes)

再次将其除以60,就可以得到小时

You can divide seconds by 60 to get the minutes

import time
seconds = time.time()
minutes = seconds / 60
print(minutes)

When you divide it by 60 again, you will get the hours


回答 11


division = 3623 // 3600 #to hours
division2 = 600 // 60 #to minutes
print (division) #write hours
print (division2) #write minutes

PS我的代码不专业


division = 3623 // 3600 #to hours
division2 = 600 // 60 #to minutes
print (division) #write hours
print (division2) #write minutes

PS My code is unprofessional