简体   繁体   English

Python时间格式为=> [天:小时:分钟:秒]至秒

[英]Python time in format => [days:hours:minutes:seconds] to seconds

I have this function that tranforms for example 我有例如转换的此功能

timeToSeconds("1:12:45:66.6")
>>>132366.6

But I admit it don't follow the DRY concept, check it out: 但我承认它不遵循DRY概念,请检查一下:

def timeToSeconds(time):
  t = time.split(':')
  try:
    if len(t) == 1:
      try:
        type(eval(t[0])) in [int, float]
      except:
        return False
      return eval(time)
    elif len(t) == 2:
      return float(t[-1]) + float(t[-2]) * 60
    elif len(t) == 3:
      return float(t[-1]) + float(t[-2]) * 60 + float(t[-3]) * 3600
    elif len(t) == 4:
      return float(t[-1]) + float(t[-2]) * 60 + float(t[-3]) * 3600 + float(t[-4]) * 86400
    else:
      return False
  except:
    return False

How would be a better way to write it? 怎么会有更好的书写方式? Note that is return False when input contains characters. 请注意,当输入包含字符时,返回False。

This should work, 这应该工作,

from datetime import timedelta

def timeToSeconds(s):
    try:
        rparts = reversed(map(float, s.split(':')))
        keys = ['seconds', 'minutes', 'hours', 'days']
        td = timedelta(**dict(zip(keys, rparts)))
        return td.total_seconds()
    except ValueError:
        return False

Fiddle 小提琴

Don't return False to indicate an error. 不要返回False来指示错误。 False == 0.0 in Python. False == 0.0在Python中。 0.0 is a valid result for "0:0:0:0.0" . 0.0"0:0:0:0.0"的有效结果。 You could allow exceptions to propagate instead: 您可以允许例外传播:

def to_sec(timedelta_string, factors=(1, 60, 3600, 86400)):
    """[[[days:]hours:]minutes:]seconds -> seconds"""
    return sum(x*y for x, y in zip(map(float, timedelta_string.split(':')[::-1]), factors))

Or if you need to suppress exceptions then return None : 或者,如果您需要抑制异常,则返回None

def timeToSeconds(time, default=None):
    try:
        return to_sec(time)
    except ValueError:
        return default
def timeToSeconds(time):
    multi = [1,60,3600,86400]
    try:
        time = map(float,time.split(":"))
        t_ret = 0
        for i,t in enumerate(reversed(time)):
            t_ret += multi[i] * t
        return t_ret
    except ValueError:
        return None

print timeToSeconds("1:12:45:66.6")
print timeToSeconds("12:45:66.6")
print timeToSeconds("45:66.6")
print timeToSeconds("66.6")
print timeToSeconds("c")

Output: 输出:

132366.6
45966.6
2766.6
66.6
None

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

相关问题 Python 以天、小时、分钟、秒表示的经过时间 - Python Elapsed Time as Days, Hours, Minutes, Seconds 在 Python 中将秒转换为天、小时、分钟和秒 - Converting seconds into days, hours, minutes & seconds in Python 如何在 Python 中将天转换为小时、分钟和秒 - How transform days to hours, minutes and seconds in Python 如何将以天、小时、分钟和秒为单位的时间转换为仅秒? - How to convert time in days, hours, minutes, and seconds to only seconds? 在Python中将秒转换为星期几小时几分秒 - Convert seconds to weeks-days-hours-minutes-seconds in Python 将秒转换为天,小时,分钟和秒 - Converting Seconds into days, hours, minutes, and seconds 如何在 Python 中将经过时间从秒格式化为小时、分钟、秒和毫秒? - How to format elapsed time from seconds to hours, minutes, seconds and milliseconds in Python? Python-将时间转换为小时和分钟,而不是秒 - Python - convert time to hours and minutes, not seconds Python计算时差,在1中给出“年、月、日、时、分和秒” - Python calculating time difference, to give ‘years, months, days, hours, minutes and seconds’ in 1 如何在Python / Django中将此持续时间转换为天/小时/分钟/秒? - How to convert this duration into days/hours/minutes/seconds in Python/Django?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM