views:

71

answers:

2

Is there a good method to convert a string representing time in the format of [m|h|d|s|w] (m= minutes, h=hours, d=days, s=seconds w=week) to number of seconds? I.e.

def convert_to_seconds(timeduration):
    ...

convert_to_seconds("1h")
-> 3600

convert_to_seconds("1d")
-> 86400

etc?

Thanks!

+4  A: 

I recommend using the timedelta class from the datetime module:

from datetime import timedelta

UNITS = {"s":"seconds", "m":"minutes", "h":"hours", "d":"days", "w":"weeks"}

def convert_to_seconds(s):
    count = int(s[:-1])
    unit = UNITS[ s[-1] ]
    td = timedelta(**{unit: count})
    return td.seconds + 60 * 60 * 24 * td.days

Internally, timedelta objects store everything as microseconds, seconds, and days. So while you can give it parameters in units like milliseconds or months or years, in the end you'll have to take the timedelta you created and convert back to seconds.

In case the ** syntax confuses you, it's the Python apply syntax. Basically, these function calls are all equivalent:

def f(x, y): pass

f(5, 6)
f(x=5, y=6)
f(y=6, x=5)

d = {"x": 5, "y": 6}
f(**d)
Eli Courtwright
I swear I did not copy your answer ;-) +1 and I think I'll delete mine.
David Zaslavsky
+5  A: 

Yes, there is a good simple method that you can use in most languages without having to read the manual for a datetime library. This method can also be extrapolated to ounces/pounds/tons etc etc:

seconds_per_unit = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}

def convert_to_seconds(s):
    return int(s[:-1]) * seconds_per_unit[s[-1]]
John Machin
Haha, +1 and bravo, I'm embarrassed that this didn't occur to me! I still recommend that everyone learn how to use the `datetime` library and the `timedelta` class for this kind of task, since in many cases it will be the most convenient option. However, I must confess that your solution is a better one than mine for this particular question.
Eli Courtwright
Yeah +1 this is quite a simple, elegant method for achieving what I wanted.. Thanks!
Andrew