【问题标题】:how to convert an alphanumeric string into time formatting?如何将字母数字字符串转换为时间格式?
【发布时间】:2021-04-14 21:19:04
【问题描述】:

我有一些反应时间作为字母数字字符串(例如“2m34s235”、“23s98”)。我想将这些字符串转换为传统的时间格式(例如'00:02:34.235'、'00:00;23.98')。当字符串包含分钟、秒和毫秒时,我的程序可以很好地完成这项工作。但是,在某些情况下,我的字符串只包含分钟和毫秒数字,但不包含秒(例如“1m567”)。所以,对于这些情况,我的输出不是我想要的。对于这种情况,一个好的输出是 00:01:00,567')。谁能帮我这个?非常感谢!

到目前为止我的代码如下:

list_of_strings= ['6m874','1m767','7m4s123','5s678','3m5s,429','7m45s,346','4m2s,345','23s,98', '1s,962', '5s,337']


new_list = [s.replace("s", "") for s in list_of_strings]
new_l=[s.replace(",", ".") for s in new_list]
tm=[]

for i in new_l:
    if 'm' and 's' in i:
        c='00:0'+str(i)
        c1=c.replace('m',':')
        tm.append(c1)
    elif 'm' in i:
        e=c='00:0'+str(i)
        e1=e.replace('m',':00,')
        tm.append(e1)
    elif float(i) < 10:
        a='00:00:0' + str(i)
        tm.append(a)
    else:
        b='00:00:' + str(i)
        tm.append(b)


for x in tm:
    print(x)

我得到的这个样本的输出是:

00:06:00,874 - 00:01:00,767 - 00:07:00,4123 - 00:00:5678 - 00:03:00,5.429 - 00:07:00,45.346 - 00:04:00,2.345 - 00:00:23.98 - 00:00:01.962 - 00:00:05.337 -

我想要的输出是:

00:06:00.874 - 00:01:00.767 - 00:07:04.123 - 00:00:05.678 - 00:03:05.429 - 00:07:45.346 - 00:04:2.345 - 00:00:23.98 - 00:00:01.962 - 00:00:05.337 -

【问题讨论】:

  • 如果你能写到这么多代码,是什么阻止你写更多的代码来覆盖更多的案例?
  • 你的代码应该如何知道1m1是指1分1秒还是1分1毫秒?
  • @mkrieger1 我认为秒后总是s
  • 除非我遗漏了什么,这是一个非常简单的修复。查看您的第二个replace 声明。为什么:00 后面有个逗号?将其更改为句点。之后输出对我来说是正确的。可能还有其他 cmets 中提到的其他问题,但这至少解决了手头的问题
  • 为什么有些字符串中有逗号?

标签: python string time


【解决方案1】:

这是对代码的修复。首先,我从字符串中删除了逗号 (,)。其次,从几分钟到几秒钟,最后到毫秒。此外,分开检查“m”和“s”。除此之外,我添加了一个检查分钟和秒数是否小于10,在这种情况下我会在它前面添加一个0,否则就取数字。

这给出了您想要的结果,但在您的情况下,我也会添加一个毫秒检查,以便所有 ms 结果都包含 3 个字符(098 而不是 98)

list_of_strings= ['6m874','1m767','7m4s123','5s678','3m5s,429','7m45s,346','4m2s,345','23s,98','1s,962 ', '5s,337']

new_list = [s.replace(",", "") for s in list_of_strings]
tm=[]

for v in new_list:
    c = '00:'
    l = v.split('m')
    if len(l) > 1:
        if int(l[0]) < 10:
            tmp = f'0{int(l[0])}:'
        else:
            tmp = f'0{int(l[0])}:'
        vs = l[1]
    else:
        vs = l[0]
        tmp = '00:'
    c = c + tmp

    l = vs.split('s')
    if len(l) > 1:
        if int(l[0]) < 10:
            tmp = f'0{int(l[0])}.{l[1]}'
        else:
            tmp = f'{int(l[0])}.{l[1]}'
    else:
        if 's' in vs:
            if int(l[0]) < 10:
                tmp = f'0{int(l[0])}.000'
            else:
                tmp = f'{int(l[0])}.000'
        else:
            tmp = f'00.{int(l[0])}'
    c = c + tmp

    tm.append(c)

for x in tm:
    print(x)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    相关资源
    最近更新 更多