【问题标题】:python3 why does my comparison change the formatting?python3 为什么我的比较会改变格式?
【发布时间】:2021-04-28 06:27:18
【问题描述】:

我有 1 次这样的格式

start_time  01:13:05

我有第二次看起来像它

Current time  01:13:10

当我计算差异时,它会产生正确的答案,但会去掉一个零

代码:

new_start_time = datetime.strptime(start_time, '%H:%M:%S')
new_current_time = datetime.strptime(str(current_time), '%H:%M:%S')
elapsed_time = new_current_time - new_start_time

产生:

elapsed time  0:00:10

10 是正确的,但 0 怎么了?我如何破解它?我需要它。

【问题讨论】:

  • elapsed_time 是一个datetime.timedelta 对象,你如何格式化它以获得你的输出?

标签: python python-3.x formatting comparison string-comparison


【解决方案1】:

添加:

elapsed_split = str(elapsed_time).split(":")
elapsed_time = int(elapsed_split[0]).zfill(2) + elapsed_split[1:]

【讨论】:

  • 我知道你在正确的轨道上,但我找不到分裂。是不是贬值了? Google 只提取非常旧的 URL -> AttributeError: 'datetime.timedelta' object has no attribute 'split'
  • 我编辑了将变量转换为 str 的答案,对不起
  • 我很抱歉,但我看不出有什么不同。
  • str(elapsed_time).split(":") elapsed_time 转换为str再拆分
猜你喜欢
  • 2016-06-24
  • 2013-03-23
  • 1970-01-01
  • 2015-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-20
相关资源
最近更新 更多