Parse hours without leading zeroes by strptime in Python

前端 未结 3 877
死守一世寂寞
死守一世寂寞 2021-01-20 11:39

Suppose you have time in this format:

a = [..., 800.0, 830.0, 900.0, 930.0, 1000.0, 1030.0, ...]

The problem is that leading zeroes for hou

3条回答
  •  鱼传尺愫
    2021-01-20 12:08

    If those are really float literals in there vs strings, you can do this:

    a=[800., 830., 900., 930., 1000., 1030.]
    hours=[time.strptime('{:04.0f}'.format(f), '%H%M') for f in a]
    

    That will round the decimal if any (1033.66666 would be 1034 hence becoming 10:34 AM)

    You can also truncate like so:

    [800.0, 830.0, 900.0, 930.0, 1000.0, 1030.0, 1033.3333333, 1033.66666]
    hours=[time.strptime(str(f).split('.')[0], '%H%M') for f in a]
    

    edit from comments

    If you have values outside the range, you do this:

    a=[800., 830., 900., 930., 1000., 1030., 2400.]
    hours=[time.strptime(s,'%H%M') for s in ['{:04.0f}'.format(f) if f <2400 else '0000' for f in a]]
    

    or, you can make your original code work that way as well:

    [time.strptime(i,'%H%M') for i in[str(int(f)) if f<2400 else '0000' for f in a]]
    

提交回复
热议问题