简体   繁体   中英

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:

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.

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 == 0.0 in Python. 0.0 is a valid result for "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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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