在python中找到2次的最简单的方法是什么? [英] What is the simplest way to find the difference between 2 times in python?

查看:133
本文介绍了在python中找到2次的最简单的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个时间值,其类型为$ code> datetime.time 。我想找到他们的区别。明显的做法是t1 - t2,但这不行。它适用于类型为 datetime.datetime 的对象,但不适用于 datetime.time 。那么最好的方法是什么?

I have 2 time values which have the type datetime.time. I want to find their difference. The obvious thing to do is t1 - t2, but this doesn't work. It works for objects of type datetime.datetime but not for datetime.time. So what is the best way to do this?

推荐答案

首先,请注意,datetime.time是一个时间,独立在某一天,因此任何两个datetime.time值之间的差异将不到24小时。

Firstly, note that a datetime.time is a time of day, independent of a given day, and so the different between any two datetime.time values is going to be less than 24 hours.

一种方法是转换datetime.time值成为可比的值(如毫秒),并找到差异。

One approach is to convert both datetime.time values into comparable values (such as milliseconds), and find the difference.

t1, t2 = datetime.time(...), datetime.time(...)

t1_ms = (t1.hour*60*60 + t1.minute*60 + t1.second)*1000 + t1.microsecond
t2_ms = (t2.hour*60*60 + t2.minute*60 + t2.second)*1000 + t2.microsecond

delta_ms = max([t1_ms, t2_ms]) - min([t1_ms, t2_ms])

这有点跛脚,但它有效。

It's a little lame, but it works.

这篇关于在python中找到2次的最简单的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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