Parse hours without leading zeroes by strptime in Python

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

    You can extract hours, minutes without strptime() in this case:

    >>> from datetime import time
    >>> a = [800., 830., 900., 930., 1000., 1030., 30., 2400.]
    >>> [time(*divmod(int(f) % 2400, 100)) for f in a]
    [datetime.time(8, 0), 
     datetime.time(8, 30), 
     datetime.time(9, 0), 
     datetime.time(9, 30),
     datetime.time(10, 0),
     datetime.time(10, 30),
     datetime.time(0, 30),
     datetime.time(0, 0)]
    

    If you want to use strptime() for whatever reason; you could concisely get the required format using x % y:

    >>> ["%04.0f" % (f % 2400) for f in a]
    ['0800', '0830', '0900', '0930', '1000', '1030', '0030', '0000']
    

提交回复
热议问题