【发布时间】: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'
【问题讨论】: