【问题标题】:Convert a time string into a decimal number of hours? [duplicate]将时间字符串转换为十进制小时数? [复制]
【发布时间】:2013-03-04 18:32:29
【问题描述】:

如何将“12:30”或“5:51:23”之类的字符串转换为表示 Python 中经过的小时数的十进制数?

【问题讨论】:

  • 当前问题和标记为重复的问题解决了不同的问题。针对重复问题发布的解决方案未解决不完整的时间字符串,例如“12:30”。投票重新开放

标签: python


【解决方案1】:

相当简单的字符串分割和数学运算:

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)

如果只给出一个数字,如@9​​87654322@,则返回3.0。如果给定两个冒号分隔的值,例如"4:57",这将返回4.95。如果给出了三个以冒号分隔的值,例如"14:36:27",这将返回14.6075

【讨论】:

    【解决方案2】:

    可能的解决方案

    >>> 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
    

    【讨论】:

    • 将 HMS 更改为 [1, 1.0/60, 1.0/3600],dec_time 将以小时为单位。可能不需要除以 3600。
    【解决方案3】:
    >>> float('5:51:23'.split(':')[0])
    5.0
    

    【讨论】:

    • 从 OP 的自我回答来看,我猜这还不够。
    • 也许,最终他会决定答案是否是他想要的。在这种情况下,我严格遵守要求和KISS principle
    猜你喜欢
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多