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

Python:使用dict zip在浮点数据类型中将字符串转换为日期失败,python,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 =

我想将字符串转换为日期。转换器使用“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')

有人能告诉我怎么做吗?

只需将数据类型从
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\u string)
将根据数字分割输入字符串。如果您根据
\d
分割输入,则将
作为输出。

只需将数据类型从
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\u string)
将根据数字分割输入字符串。如果您根据
\d
分割输入,那么您将得到
作为输出。

如前所述,您可以使用
浮点
而不是
整数
,但这会导致一些奇怪的操作组合。我也会简化,找到有效的
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))

如前所述,您可以使用
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.5h15m
应该是
1h45m
。。。允许像
1.5241341425h
这样的东西看起来很奇怪实际上,我将其用于工程数据。是的,看起来很奇怪。但它确实发生了。而且不知何故,日期也只有“1.5小时”。顺便说一句,谢谢你的评论:)允许这种格式似乎很奇怪。。。当然
1.5h15m
应该是
1h45m
。。。允许像
1.5241341425h
这样的东西看起来很奇怪实际上,我将其用于工程数据。是的,看起来很奇怪。但它确实发生了。而且不知何故,日期也只有“1.5小时”。顺便说一句,谢谢你的评论:)这是一个很好的方法+1灵活的方法+1.