我有多次存储在一个数组中,我需要将其转换为24小时。
[' 06:00a-11:00a',' 07:00p-11:00p',' 09:00a-04:00p',' 09:00a-04:00p',' 10:00a-04:00p',' 10:00A-03:00P']
我不能使用%r,因为符号不是它" am"或" pm"。
最好的方法是什么?
答案 0 :(得分:2)
您只需要每次都附加一个'm'
,strptime
会解析它。
list(map(lambda s: datetime.strptime(s+'m', '%I:%M%p'), s) for s in (s.strip().split('-') for s in l)
输出(为了清晰起见而进行了编辑):
[[datetime(…, 06, 0), datetime(…, 11, 0)],
[datetime(…, 19, 0), datetime(…, 23, 0)],
[datetime(…, 09, 0), datetime(…, 16, 0)],
[datetime(…, 09, 0), datetime(…, 16, 0)],
[datetime(…, 10, 0), datetime(…, 16, 0)],
[datetime(…, 10, 0), datetime(…, 15, 0)]]
def parse(times):
split_times = (s.strip().split('-') for s in times)
parsed_times = []
for time_group in split_times:
parsed_group = []
for time_str in time_group:
parsed_time = datetime.strptime(time_str + 'm', '%I:%M%p')
parsed_group.append(parsed_time)
parsed_times.append(parsed_group)
return parsed_times
答案 1 :(得分:0)
它有点笨重,但基本上,你可以拿每个字符串并检查最后一个字符。如果它是a
,请丢弃它。如果它是p
,则在冒号前面加上12:
def translate_times(s):
# Remove space at the begining and split according to the -
each = s[1:].split('-')
for i in range(len(each)):
if each[i][5] == 'a':
each[i] = each[i][0:5]
else:
each[i] = str(int(each[i][0:2]) + 12) + ':' + each[i][3:5]
return '-'.join(each)
orig = [' 06:00a-11:00a', ' 07:00p-11:00p', ' 09:00a-04:00p', ' 09:00a-04:00p', ' 10:00a-04:00p', ' 10:00a-03:00p']
result = [translate_times(x) for x in orig]
答案 2 :(得分:0)
这可能不是最快的解决方案,但会提供您所要求的输出:
old = [' 06:00a-11:00a', ' 07:00p-11:00p', ' 09:00a-04:00p', ' 09:00a-04:00p', ' 10:00a-04:00p', ' 10:00a-03:00p']
import time
修复上午/下午问题:
am = list(map(lambda x:x.replace('a','am'),old))
pm = list(map(lambda x:x.replace('p','pm'),am))
删除空格并拆分' - '字符:
times = [i.strip() for i in pm];times = [i.split('-') for i in times]
列出理解以将转换时间返回到请求的格式:
[i +' - '+ j for i,j in zip(timelist [:: 2],timelist [1 :: 2])]
['6:00-11:00',
'19:00-23:00',
'9:00-16:00',
'9:00-16:00',
'10:00-16:00',
'10:00-15:00']