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

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

    I usually need to support raw numbers, string numbers and string numbers ending in [m|h|d|s|w].

    This version will handle: 10, "10", "10s", "10m", "10h", "10d", "10w".

    Hat tip to @Eli Courtwright's answer on the string conversion.

    UNITS = {"s":"seconds", "m":"minutes", "h":"hours", "d":"days", "w":"weeks"}
    
    def convert_to_seconds(s):
        if isinstance(s, int):
            # We are dealing with a raw number
            return s
    
        try:
            seconds = int(s)
            # We are dealing with an integer string
            return seconds
        except ValueError:
            # We are dealing with some other string or type
            pass
    
        # Expecting a string ending in [m|h|d|s|w]
        count = int(s[:-1])
        unit = UNITS[ s[-1] ]
        td = timedelta(**{unit: count})
        return td.seconds + 60 * 60 * 24 * td.days
    

提交回复
热议问题