将日期和时间(小时x分钟x秒)转换为仅时间 [英] Convert Days and Time (Hours x Minutes x Seconds) to Time only

查看:97
本文介绍了将日期和时间(小时x分钟x秒)转换为仅时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框,在其中我对两个不同的日期进行了区别,以获取小时和分钟的区别,例如:

I have a Dataframe in which I am making the difference between two different dates to get the difference in Hours and Minutes, for example:

 start_date = '2018-07-03 16:03:00'
 data_final = '2018-07-05 00:00:00'
 duration = data_final - start_date

我要查找的结果是 '31:57:00',即两个日期之间的总时差.但是我得到的结果是:"1天,7:57:00" (每24小时写为1天).

The result I'm looking for is '31: 57: 00 ', or the total time difference between the two dates. But the result I have is: '1 day, 7:57:00' (Every 24 hours it writes as 1 day).

我尝试使用以下语句将其转换为XMinutesHours格式:

I tried converting it to an XMinutesHours format with the statement:

print (datetime.datetime.strptime (duration, "%H:%M:%S"))

但是我得到了错误:

ValueError:时间数据"1天,7:57:00"与格式%H:%"不匹配M:%S'

ValueError: time data '1 day, 7:57:00' does not match format '% H:% M:% S'

有什么主意吗?

推荐答案

您需要以小时,分钟和秒为单位计算等效项,您可以实现一个函数来获取该值,例如:

You need to calculate the equivalent in hours, minutes and seconds, you could implement a function to get this value, for example:

from datetime import datetime

def get_duration(duration):
    hours = int(duration / 3600)
    minutes = int(duration % 3600 / 60)
    seconds = int((duration % 3600) % 60)
    return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)

format_str = '%Y-%m-%d %H:%M:%S'
start_date_str = '2018-07-03 16:03:00'
end_date_str = '2018-07-05 00:00:00'

start_date = datetime.strptime(start_date_str, format_str)
end_date = datetime.strptime(end_date_str, format_str)
duration = (end_date - start_date).total_seconds()

print(get_duration(duration))

这篇关于将日期和时间(小时x分钟x秒)转换为仅时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆