【问题标题】:Python - Parsing string to timedelta when hours value is greater than 24Python - 当小时值大于 24 时将字符串解析为 timedelta
【发布时间】:2021-05-28 06:35:32
【问题描述】:

我正在运行每日报告,我想记录每天运行所需的时间。 我通过在开始和结束时调用 datetime.datetime.now() 得到一个 report_time timedelta 对象,然后得到两个值之间的差异。

我有一个包含两行的文本文件。第 1 行是今天的运行时。第 2 行是总累积运行时间。

问题是,当我尝试将第 2 行解析为 datetime.datetime 对象(然后创建一个 timedelta 对象以添加今天的报告时间)时,如果累积运行时间超过 24 小时,我不会这样做(我猜是因为它不再是一个有效的日期。

知道如何解决这个问题(本质上是在不符合 datetime.datetime 格式时将字符串解析为 time.delta 对象?

代码:

report_stats = f.read()
today_cumulative_reports_time = report_stats.splitlines()[0]
prev_total_reports_time = report_stats.splitlines()[1]
today_cumulative_reports_time = datetime.datetime.strptime(today_cumulative_reports_time, 
'%H:%M:%S.%f')

today_cumulative_reports_time = datetime.timedelta(hours=today_cumulative_reports_time.hour, 
minutes=today_cumulative_reports_time.minute,
                    seconds=today_cumulative_reports_time.second, 
microseconds=today_cumulative_reports_time.microsecond)
prev_total_reports_time = datetime.datetime.strptime(prev_total_reports_time, '%H:%M:%S.%f')
prev_total_reports_time = datetime.timedelta(hours=prev_total_reports_time.hour, 
minutes=prev_total_reports_time.minute,
               seconds=prev_total_reports_time.second, 
microseconds=prev_total_reports_time.microsecond)
cumulative_run_time = report_time + today_cumulative_reports_time + prev_total_reports_time
f.close()

Error:

ValueError: time data '24:54:03.294820' does not match format '%H:%M:%S.%f'

【问题讨论】:

    标签: python datetime


    【解决方案1】:

    手动解析字符串,然后构造timedelta对象:

    from datetime import timedelta
    
    time_string = '24:54:03.294820'
    hours, minutes, seconds = map(float, time_string.split(':'))
    t_delta = timedelta(hours=hours, minutes=minutes, seconds=seconds)
    print(t_delta)
     
    

    输出

    1 day, 0:54:03.294820
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      • 1970-01-01
      • 2018-09-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多