【问题标题】:How to convert outcome of timedelta into only hours如何将 timedelta 的结果转换为仅小时
【发布时间】:2021-05-14 11:20:54
【问题描述】:

我得到的持续时间的结果包括天、小时和分钟。我该怎么做才能让它只显示几个小时?

import datetime as dt

start_datetime_str = '1/04/2021 7:55'
end_datetime_str = '14/05/2021 9:55'

# convert string to date object
start_datetime_obj = dt.datetime.strptime(start_datetime_str, '%d/%m/%Y %H:%M')
end_datetime_obj = dt.datetime.strptime(end_datetime_str, '%d/%m/%Y %H:%M')

# calculate duration
duration = end_datetime_obj - start_datetime_obj
print(duration)

【问题讨论】:

标签: python datetime


【解决方案1】:

使用.hour:

duration = end_datetime_obj.hour - start_datetime_obj.hour
print(duration)

输出:

2

【讨论】:

    【解决方案2】:

    使用 total_seconds() 并除以 60 两次以从秒中获取小时数

    print(duration.total_seconds()/60/60)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 2023-01-05
      • 1970-01-01
      • 2021-10-03
      • 2018-12-02
      相关资源
      最近更新 更多