How to convert an H:MM:SS time string to seconds in Python?

前端 未结 12 1754
陌清茗
陌清茗 2020-11-29 22:14

Basically I have the inverse of this problem: Python Time Seconds to h:m:s

I have a string in the format H:MM:SS (always 2 digits for minutes and seconds), and I nee

12条回答
  •  情歌与酒
    2020-11-29 22:47

    Just a simple generalization to the great response of taskinoor

    In the context of my problem the format is similar, but includes AM or PM.

    Format 'HH:MM:SS AM' or 'HH:MM:SS PM'

    For this case the function changes to:

    def get_sec(time_str):
    """Get Seconds from time."""
    if 'AM' in time_str:
        time_str = time_str.strip('AM')
        h, m, s = time_str.split(':')
        seconds = int(h) * 3600 + int(m) * 60 + int(s)
    if 'PM' in time_str:
        time_str = time_str.strip('PM')
        h, m, s = time_str.split(':')
        seconds = (12 + int(h)) * 3600 + int(m) * 60 + int(s)
    
    return seconds 
    

提交回复
热议问题