Martin
Martin

Reputation: 58

How can I parse multiple time durations in python?

I´m working on a discord bot that has a feature to provide time durations like 1m, 2d for tempban/mutes and stuff. Currently I try to figure out how I could use more than one of these durations like 1d12h.

def convert(time):
    pos = ["s" ,"m", "h", "d","y"]
    time_dict = {"s": 1, "m": 60, "h": 3600, "d": 3600 * 24, "y": 86400 * 365}

    unit = time[-1]

    if unit not in pos:
        return -1
    try:
        val = int(time[:-1])
    except:
        return -2

    return val * time_dict[unit]

This function I currently use to convert single durations into seconds to work with that duration. But I have no plan how I can use this for multiple time durations.

I tried parse_time() of the humanfriendly module but the function only allows a string input of one duration. Is this even possible what I plan to do? Any Ideas?

Upvotes: 0

Views: 74

Answers (1)

Ferret
Ferret

Reputation: 162

There's 100 ways to do this, but without spacing I'd do this (probably not the most efficient)

def convert(timeString):
   out = 0
   current = ""
   timeDict = {"s": 1, "m": 60, "h": 3600, "d": 3600 * 24, "y": 86400 * 365}
   for char in timeString:
      if char.isdigit(): # For numbers, we will not support decimals here
         current += char # Add the number to the multiplication string
      elif char in timeDict: # Check if it's a valid key
         out += int(current) * timeDict[char] # Add the time
         current = "" # Reset the multiplication
   return out

I wrote this on my phone, pls lemme know if theres a syntax error

Upvotes: 2

Related Questions