我想创建一个小时列表,它是24小时制(以数字为单位)的元组和12小时制的字符串表示。
格式如下:
[(0, "12 AM"), (1, "1 AM), ..., (13, "1PM"), ... ]
我能够得到这样的东西
hours = [(0,"12 AM")]
hours += [(hour,str(hour) + " AM") for hour in range(1, 12)]
hours += [(12,"12 PM")]
hours += [(hour+12,str(hour) + " PM") for hour in range(1, 12)]
但我觉得有一种更清洁的方法可以做到这一点,但无法弄明白。
答案 0 :(得分:7)
import datetime as dt
hours = [(i, dt.time(i).strftime('%I %p')) for i in range(24)]
答案 1 :(得分:3)
>>> hours = [(n, "%d %s" % (n % 12 or 12, ["AM", "PM"][n > 11])) for n in range(24)]
>>> hours
[(0, '12 AM'), (1, '1 AM'), (2, '2 AM'), (3, '3 AM'), (4, '4 AM'), (5, '5 AM'), (6, '6 AM'), (7, '7 AM'), (8, '8 AM'), (9, '9 AM'), (10, '10 AM'), (11, '11 AM'), (12, '12 PM'), (13, '1 PM'), (14, '2 PM'), (15, '3 PM'), (16, '4 PM'), (17, '5 PM'), (18, '6 PM'), (19, '7 PM'), (20, '8 PM'), (21, '9 PM'), (22, '10 PM'), (23, '11 PM')]
答案 2 :(得分:0)
这是另一个单行代码:
[(hour24, '%d %s' % (hour12, (lambda x: 'AM' if x < 12 else 'PM')(hour24))) for hour12, hour24 in zip(([12]+range(1, 12)*2), range(0, 24))]
答案 3 :(得分:0)
我还找到了一种替代品,我将其用作发电机:
def dayrange(start_date):
for n in range(25):
yield start_date + i*timedelta(hours = 1)
使用start_date作为datetime.datetime对象。