Python:使用dict zip在float数据类型中将字符串转换为日期失败

时间:2015-02-03 06:51:35

标签: python

我想将字符串转换为日期。转换器是使用' m'一分钟,' h'一个小时,并且' d'一天。例如:' 1d3h50m'。 如果我输入确切的数字,它有一个正确的答案,但如果我使用浮点数则问题是错误的。例如:' 1.5d3h50m'。

这是我的剧本:

import re

def compute_time(hour_string):
    numbers = [int(i) for i in re.split('d|h|m|s', hour_string) if i != '']
    words = [i for i in re.split('\d', hour_string) if i != '']

    combined = dict(zip(words, numbers))

    return combined.get('d', 0) * 86400 + combined.get('h', 0) * 3600 + combined.get('m', 0) * 60 + combined.get('s', 0)

print compute_time('1.5h15m5s')

有人可以告诉我如何使这项工作?

2 个答案:

答案 0 :(得分:4)

正如所指出的,您可以使用float代替int,但这会导致您可以做的一些奇怪的组合。我还简化了在有效dhms成对之前查找内容,然后对这些内容求和,例如:

def compute_time(text):
    scale = {'d': 86400, 'h': 3600, 'm': 60, 's': 1}
    return sum(float(n) * scale[t] for n, t in re.findall('(.*?)([dhms])', text))

答案 1 :(得分:2)

只需将数据类型从int更改为float

numbers = [float(i) for i in re.split('d|h|m|s', hour_string) if i != '']

我建议您更改下面的代码。

def compute_time(hour_string):
    numbers = [float(i) for i in re.split('d|h|m|s', hour_string) if i != '']
    words = [i for i in re.split(r'\d+(?:\.\d+)?', hour_string) if i != '']
    combined = dict(zip(words, numbers))
    return combined.get('d', 0) * 86400 + combined.get('h', 0) * 3600 + combined.get('m', 0) * 60 + combined.get('s', 0)

print compute_time('1.6h15m5s')

re.split(r'\d+(?:\.\d+)?', hour_string)会根据数字拆分输入字符串。如果您根据\d拆分输入,那么您将获得.作为输出。