【发布时间】:2013-03-04 18:32:29
【问题描述】:
如何将“12:30”或“5:51:23”之类的字符串转换为表示 Python 中经过的小时数的十进制数?
【问题讨论】:
-
当前问题和标记为重复的问题解决了不同的问题。针对重复问题发布的解决方案未解决不完整的时间字符串,例如“12:30”。投票重新开放
标签: python
如何将“12:30”或“5:51:23”之类的字符串转换为表示 Python 中经过的小时数的十进制数?
【问题讨论】:
标签: python
相当简单的字符串分割和数学运算:
def time_string_to_decimals(time_string):
fields = time_string.split(":")
hours = fields[0] if len(fields) > 0 else 0.0
minutes = fields[1] if len(fields) > 1 else 0.0
seconds = fields[2] if len(fields) > 2 else 0.0
return float(hours) + (float(minutes) / 60.0) + (float(seconds) / pow(60.0, 2)
如果只给出一个数字,如@987654322@,则返回3.0。如果给定两个冒号分隔的值,例如"4:57",这将返回4.95。如果给出了三个以冒号分隔的值,例如"14:36:27",这将返回14.6075。
【讨论】:
可能的解决方案
>>> time_st = ["12:30" , "5:51:23"]
>>> HMS = [60*60, 60, 1]
>>> for t in time_st:
dec_time = sum(a * b for a,b in zip(HMS, map(int, t.split(":"))))
dec_time /= 3600.
print "{} = {}".format(t, dec_time)
12:30 = 12.5
5:51:23 = 5.85638888889
00:00 = 0.0
23:59 = 23.9833333333
【讨论】:
>>> float('5:51:23'.split(':')[0])
5.0
【讨论】: