如何检查两个日期时间是否在一定范围内? [英] How to check if two datetimes are within a certain range of each other?

查看:101
本文介绍了如何检查两个日期时间是否在一定范围内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个datetime64对象a和b,我想确定它们是否在彼此的一定范围内。但是,范围不对称。如果a在b的-30至120分钟之内(a比b早半小时到晚两个小时之间),则两者均在所需范围内。我的日期时间对象看起来像%m /%d /%Y%H:%M。我试着说:

I have two datetime64 objects, a and b, and I want to determine if they are within a certain range of each other. However, the range is not symmetrical. If a is within -30 and 120 minutes of b (a is between half an hour earlier and two hours later than b), the two are within the desired range. My datetime objects look like %m/%d/%Y %H:%M. I tried saying:

difference = a - b
if (-30 <= difference <= 120):
    #Do stuff

但是,这不起作用,因为差异不在几分钟之内。我不确定如何执行此比较。我知道timedelta可以用于日期时间比较,但是我不知道如何在不对称范围内使用它。

However, this doesn't work because difference is not in minutes. I am not sure how to perform this comparison. I know timedelta can be used for datetime comparisons, but I don't know how to use it with an asymmetric range like this one.

谢谢。

推荐答案

比较 timedelta 差异到另外两个 timedelta s:

Compare the timedelta difference to two other timedeltas:

from datetime import timedelta





if timedelta(minutes=-30) <= difference <= timedelta(minutes=120):

这篇关于如何检查两个日期时间是否在一定范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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