Parse hours without leading zeroes by strptime in Python

前端 未结 3 911
死守一世寂寞
死守一世寂寞 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:18

    Use zfill to add those zeros back as needed:

    hours = [time.strptime(i[:-1].zfill(4), "%H%M") for i in a]
    

    By using i[:-1] we remove that pesky trailing dot, and .zfill(4) will add enough 0 characters to the left to make it to 4 digits.

    Demo:

    >>> import time
    >>> a = ['800.', '830.', '900.', '30.']
    >>> [time.strptime(i[:-1].zfill(4), "%H%M") for i in a]
    [time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1), time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=30, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1), time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=9, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1), time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=30, tm_sec=0, tm_wday=0, tm_yday=1, tm_isdst=-1)]
    

    If they are float values instead, use the format() function on them to give you zero-padded values:

    >>> format(800., '04.0f')
    '0800'
    

    So do this:

    hours = [time.strptime(format(i % 2400, '04.0f'), "%H%M") for i in a]
    

    where % 2400 normalizes your values to the 0. to 2399. range.

提交回复
热议问题