【问题标题】:A function that can take timestamp from user as input and convert it into a total number of seconds一个可以将用户的时间戳作为输入并将其转换为总秒数的函数
【发布时间】:2022-01-23 00:19:57
【问题描述】:

我一直在尝试编写一个脚本,该脚本将接受来自用户的文本作为时间戳,将其转换为总秒数,然后启动一个计时器。例如

Time: 1h:1m:30s
>> 3690s

我想出了这个从用户那里获取时间戳的解决方案

def toSecond(timestring):
    t = 0
    remove_space = lambda str: str.replace(" ", "")
    timestring = remove_space(timestring)

    try:
        if (":") in timestring:
            time = timestring.split(":")
            try:
                for i in time:
                    if i[-1] in ("s", "S" "M", "m", "h", "H") and i[0].isnumeric():
                        if i[-1] in ("h", "H"):
                            t += int(i[:-1]) * 3600
                        elif i[-1] in ("m", "M"):
                            t += int(i[:-1]) * 60
                        else:
                            t += int(i[:-1])
                    else:
                        print("No num or no char Provided")
            except IndexError:
                print("nothing provided")
        else:
            if (
                timestring[-1] in ("s", "S" "M", "m", "h", "H")
                and timestring[0].isnumeric()
            ):
                if timestring[-1] in ("h", "H"):
                    t += int(timestring[:-1]) * 3600
                elif timestring[-1] in ("m", "M"):
                    t += int(timestring[:-1]) * 60
                else:
                    t += int(timestring[:-1])

            elif timestring.isnumeric():
                t += int(timestring)

            else:
                print("No time Provided")
    except ValueError:
        print("Error Value")

    return t

这个解决方案有效,但是,我想知道如何才能更短、更有效地做到这一点。

【问题讨论】:

    标签: python python-3.x time timestamp


    【解决方案1】:

    提取小时、分钟和秒,然后像这样使用datetime.timedelta

    from datetime import timedelta
    
    ts = "1h:1m:30s"
    time_indicators = ["H", "h", "M", "m", "S", "s"]
    for ind in time_indicators:
        ts = ts.replace(ind, "")
    
    hours, minutes, seconds = ts.split(":")
    print(timedelta(hours=int(hours), minutes=int(minutes), seconds=int(seconds)).total_seconds())
    
    
    
    
    

    【讨论】:

      【解决方案2】:

      如果您想捕捉错误的用户输入 - 使用 split 然后使用正则表达式:

      import re
      
      UNIT_TO_SECONDS = {
          'h': 3600,
          'm': 60,
          's': 1
      }
      
      def parse_part(part):
          match = re.match(r'^(\d+)([HhMmSs])$', part)
          if match is None:
              raise ValueError(f'"{part}" is not a valid part of time')
          return (int(match.group(1)),match.group(2).lower() )
      
      def to_seconds_part(part):
          nb, unit = parse_part(part)
          return nb * UNIT_TO_SECONDS[unit]
      
      
      def to_seconds(user_input):
          parts = user_input.split(':')
          parts_seconds = list(map(to_seconds_part, parts))
          return sum(parts_seconds)
      

      【讨论】:

        猜你喜欢
        • 2021-07-11
        • 2017-09-08
        • 1970-01-01
        • 2013-08-19
        • 1970-01-01
        • 1970-01-01
        • 2016-03-04
        • 2013-03-09
        相关资源
        最近更新 更多