我有一个字典,其中包含日期和时间列表(以字符串形式).
input = {
'2016-02-11': [
u'30m',
u'2h 30m',
u'1h',
u'2h',
u'30m',
u'1h',
u'30m',
u'1h',
u'45m'
],
'2016-01-27': [
u'1d'
],
'2016-01-28': [
u'30m',
u'5h',
u'30m',
u'1h',
u'45m'
],
'2016-01-29': [
u'30m',
u'6h 30m',
u'45m'
],
'2016-02-09': [
u'30m',
u'15m',
u'4h',
u'15m',
u'2h',
u'45m'
]
}
如何在列表中添加每个时间?这样新的字典看起来像这样:
output = {
'2016-02-11': [
'9h 45m'
],
'2016-01-27': [
'8h'
],
'2016-01-28': [
'7h 45m'
],
'2016-01-29': [
'7h 45m'
],
'2016-02-09': [
'7h 45m'
]
}
一些说明:
> 1d == 8h
>我想计算每天一个人的timeSpent,这就是我需要添加列表的原因
>如果有人想知道,使用此API从Jira收集数据
解决方法:
制作将1h 30m转换为90(意味着90分钟)的字符串的辅助函数,以及反向函数:
def parse_time(s):
""" '1h 30m' -> 90 """
m = 0
for x in s.split():
if x.endswith('d'):
m += int(x[:-1]) * 60 * 8 # NOTE: 8, not 24
elif x.endswith('h'):
m += int(x[:-1]) * 60
elif x.endswith('m'):
m += int(x[:-1])
return m
def to_time(m):
""" 90 -> '1h 30m' """
d, m = divmod(m, 60 * 8) # NOTE: 8, not 24
h, m = divmod(m, 60)
ret = []
if d:
ret.append('{}d'.format(d))
if h:
ret.append('{}h'.format(h))
if m:
ret.append('{}m'.format(m))
return ' '.join(ret) or '0m'
用法:将时间字符串转换为int值(分钟),并将这些值相加,将分钟转换回时间字符串:
>>> parse_time('1h 30m')
90
>>> to_time(90)
'1h 30m'
>>> to_time(parse_time('1h 30m') + parse_time('30m'))
'2h'
>>> times = {
... '2016-02-11': [ u'30m', u'2h 30m', u'1h', u'2h', u'30m',
... u'1h', u'30m', u'1h', u'45m' ],
... '2016-01-27': [ u'1d' ],
... '2016-01-28': [ u'30m', u'5h', u'30m', u'1h', u'45m' ],
... '2016-01-29': [ u'30m', u'6h 30m', u'45m' ],
... '2016-02-09': [ u'30m', u'15m', u'4h', u'15m', u'2h', u'45m' ]
... }
>>> {d: to_time(sum(map(parse_time, ts))) for d, ts in times.items()}
{'2016-01-27': '1d',
'2016-01-28': '7h 45m',
'2016-01-29': '7h 45m',
'2016-02-09': '7h 45m',
'2016-02-11': '1d 1h 45m'}
如果需要日期字符串列表:
>>> {d: [to_time(sum(map(parse_time, ts)))] for d, ts in times.items()}
{'2016-01-27': ['1d'],
'2016-01-28': ['7h 45m'],
'2016-01-29': ['7h 45m'],
'2016-02-09': ['7h 45m'],
'2016-02-11': ['1d 1h 45m']}