根据 Python 中的日期范围检查日期 [英] Checking date against date range in Python

查看:20
本文介绍了根据 Python 中的日期范围检查日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期变量:2011-01-15,如果所述日期在今天的 3 天内,我想返回一个布尔值.我不太确定如何在 Python 中构造它.我只处理日期,而不是日期时间.

I have a date variable: 2011-01-15 and I would like to get a boolean back if said date is within 3 days from TODAY. Im not quite sure how to construct this in Python. Im only dealing with date, not datetime.

我的工作示例是宽限期".用户登录我的网站,如果宽限期在今天的 3 天内,则该用户的其他脚本等将被省略.

My working example is a "grace period". A user logs into my site and if the grace period is within 3 days of today, additional scripts, etc. are omitted for that user.

我知道你可以在 Python 的日期模块中做一些花哨/复杂的事情,但我不知道去哪里找.

I know you can do some fancy/complex things in Python's date module(s) but Im not sure where to look.

推荐答案

在 Python 中检查范围可以使用 a <= x <= b:

In Python to check a range you can use a <= x <= b:

>>> import datetime
>>> today = datetime.date.today()
>>> margin = datetime.timedelta(days = 3)

>>> today - margin <= datetime.date(2011, 1, 15) <= today + margin
True

这篇关于根据 Python 中的日期范围检查日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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