Convert time string expressed as [m|h|d|s|w] to seconds in Python

后端 未结 5 532
说谎
说谎 2021-01-02 10:02

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.

5条回答
  •  孤街浪徒
    2021-01-02 10:38

    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)
    

提交回复
热议问题