Python时间比较 [英] Python time comparison

查看:170
本文介绍了Python时间比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何比较python中的时间?



我看到日期比较可以做,还有timedelta,但我很想知道检查当前时间(来自datetime.now())是否早于,等于或晚于指定时间(例如8am),而不管日期。

解决方案

不能比较某个时间点(例如现在)与不固定的重复事件(每天上午8点发生) p>

您可以检查现在是今天上午8:00之前还是之后

 >>> import datetime 
>>>> now = datetime.datetime.now()
>>>> today8am = now.replace(hour = 8,minute = 0,second = 0,microsecond = 0)
>>>>现在, today8am
True
>>> now == today8am
False
>>>现在> today8am
False


How do I compare times in python?

I see that date comparisons can be done and there's also "timedelta", but I'm struggling to find out how to check if the current time (from datetime.now()) is earlier, the same, or later than a specified time (e.g. 8am) regardless of the date.

解决方案

You can't compare a specific point in time (such as "right now") against an unfixed, recurring event (8am happens every day).

You can check if now is before or after today's 8am:

>>> import datetime
>>> now = datetime.datetime.now()
>>> today8am = now.replace(hour=8, minute=0, second=0, microsecond=0)
>>> now < today8am
True
>>> now == today8am
False
>>> now > today8am
False

这篇关于Python时间比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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