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

后端 未结 5 531
说谎
说谎 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:21

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

提交回复
热议问题