Python时间格式=> [天:小时:分:秒]到秒

时间:2014-12-25 21:02:01

标签: python datetime time dry seconds

我有这个转换的功能,例如

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

但我承认它不遵循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

如何更好地编写它?请注意,当输入包含字符时返回False。

3 个答案:

答案 0 :(得分:2)

这应该有效,

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

答案 1 :(得分:1)

请勿返回False表示错误。 Python中的False == 0.00.0"0:0:0:0.0"的有效结果。您可以允许异常传播:

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

或者,如果您需要禁止例外,请返回None

def timeToSeconds(time, default=None):
    try:
        return to_sec(time)
    except ValueError:
        return default

答案 2 :(得分:0)

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

输出:

132366.6
45966.6
2766.6
66.6
None