从我的python代码中,我得到了如下所示的结果列表。
list1 = [{'start': 'Mon12', 'end': '3:30'}, {'start': '7', 'end':
'10:30'}]
在这里,我需要将上面的list1转换为24小时的日期格式,如下所示。
list2 = [{'start': 12, 'end': 1530}, {'start': 1900, 'end': 2230}]
如何在python中执行此操作?
答案 0 :(得分:0)
首先,您应该区分上述评论中提到的am / pm。
但是,如果您知道上述输出列表建议的所有这些时间都是pm,那么您可以遍历每个值,删除不需要的字符并添加1200,如下所示:
list1 = [{'start' : 'Mon12', 'end' : '3:30'},
{'start' : '7', 'end' : '10:30'}]
def shift24(listofdict):
shift = 1200
resultlist = listofdict
# loop through list of dictionaries, then through each dictionary
for d in resultlist:
for key in d:
# create a mask by stripping each value of numbers
# (uses a list comp of numerical ASCII characters)
mask = d[key].strip(''.join([chr(x) for x in range(48,58)]))
# use that mask to get just the numbers
maskstrip = d[key].replace(mask,'')
# evaluate the length of string and convert to right format
# assuming if len(str) < 3: we just have the hours and need
# to mulitply by 100
if len(maskstrip) < 3:
result = ('%04d' % (int(maskstrip) * 10**2))
else:
result = ('%04d' % int(maskstrip))
# shift these values by 1200 hours and return list
#use str() if you want to output strings not integers
d[key] = int(result) + shift
return resultlist
print(shift24(list1))
输出结果为:
[{'start': 2400, 'end': 1530}, {'start': 1900, 'end': 2230}]
希望有所帮助,根据您的需求进行改变