繁体   English   中英

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

[英]How do I convert seconds to hours, minutes and seconds?

我有一个 function 可以在几秒钟内返回信息,但我需要以小时:分钟:秒的形式存储该信息。

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

您可以使用datetime.timedelta函数:

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

我很难说出一个简单的方法(至少我不记得语法),但可以使用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 之后截断

使用datetime<\/code>时间:<\/h1>

使用':0>8'<\/code>格式:<\/h3>
 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'<\/code><\/pre>

没有':0>8'<\/code>格式:<\/h3>
 "{}".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'<\/code><\/pre>

使用time<\/code> :<\/h1>
 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<\/code><\/pre>"

这是我的快速技巧:

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

以下套装对我有用。

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']

这就是我得到它的方式。

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)

如果你需要获取datetime.time值,你可以使用这个技巧:

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

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

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

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

您可以使用大于 0 的任何数字代替1这里我们使用datetime.fromordinal将始终返回time分量为零的datetime对象这一事实。

小时 (h) 由秒除以 3600 (60 分钟\/小时 * 60 秒\/分钟) 计算得出

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

同样,秒 (s) 按小时和分钟的余数计算。

休息只是字符串格式!

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

有点离题的答案,但可能对某人有用

    def time_format(seconds: int):
    if seconds is not None:
        seconds = int(seconds)
        d = seconds // (3600 * 24)
        h = seconds // 3600 % 24
        m = seconds % 3600 // 60
        s = seconds % 3600 % 60
        if d > 0:
            return '{:02d}D {:02d}H {:02d}m {:02d}s'.format(d, h, m, s)
        elif h > 0:
            return '{:02d}H {:02d}m {:02d}s'.format(h, m, s)
        elif m > 0:
            return '{:02d}m {:02d}s'.format(m, s)
        elif s > 0:
            return '{:02d}s'.format(s)
    return '-'

如果您还需要以浮点数形式访问小时、分钟和秒,则dateutil.relativedelta<\/code>很方便。 datetime.timedelta<\/code>不提供类似的接口。

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)))

就我而言,我想实现格式“HH:MM:SS.fff”。 我是这样解决的:

timestamp = 28.97000002861023
str(datetime.fromtimestamp(timestamp)+timedelta(hours=-1)).split(' ')[1][:12]
'00:00:28.970'

如果您希望将日期上“自午夜以来的秒数”的单个值转换为日期时间对象或带有 HH:MM:SS 的字符串,则上述解决方案将起作用,但我登陆此页面是因为我想这样做在熊猫的整个数据框列上。 如果其他人想知道如何一次为多个值执行此操作,那么最终对我有用的是:

 mydate='2015-03-01'
 df['datetime'] = datetime.datetime(mydate) + \ 
                  pandas.to_timedelta(df['seconds_since_midnight'], 's')

这是我一直使用的一种方式:(不管它多么低效)

seconds = 19346
def zeroes (num):
    if num < 10: num = "0" + num
    return num

def return_hms(second, apply_zeroes):
    sec = second % 60
    min_ = second // 60 % 60
    hrs = second // 3600
    if apply_zeroes > 0:
       sec = zeroes(sec)
       min_ = zeroes(min_)
       if apply_zeroes > 1:
           hrs = zeroes(hrs)
    return "{}:{}:{}".format(hrs, min_, sec)

print(return_hms(seconds, 1))

这是一个简单的程序,它读取当前时间并将其转换为以小时、分钟和秒为单位的时间

import time as tm #import package time
timenow = tm.ctime() #fetch local time in string format

timeinhrs = timenow[11:19]

t=tm.time()#time.time() gives out time in seconds since epoch.

print("Time in HH:MM:SS format is: ",timeinhrs,"\nTime since epoch is : ",t/(3600*24),"days")

我在这里查看了所有答案,但仍然尝试了自己的答案

def a(t):
  print(f"{int(t/3600)}H {int((t/60)%60) if t/3600>0 else int(t/60)}M {int(t%60)}S")

这是一个快速的单行:

(s = 秒)

':'.join([str(int(s/60/60 % 60)), str(int(s/60 % 60)), str(int(s%60))])

Output:

'12:31:20'

我想出的自定义解决方案:

import math

hours = math.floor(seconds / 3600)
seconds -= hours * 3600

minutes = math.floor(seconds / 60)
seconds -= minutes * 60

seconds = math.floor(seconds)

return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM