如何检查日期是否在中午之前 [英] How to check if a date time is before midday

查看:120
本文介绍了如何检查日期是否在中午之前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python中有一个datetime对象,我想创建一个函数来检查输入是在日期时间的早上还是下午(即,在12点之前或之后)。如何手动创建时间 12:00 ,我可以使用大于或小于此符号( > )?

解决方案

调用 datetime.datetime.time()方法 datetime 对象上,并将其与 datetime.time()对象进行比较: p>

 如果dt.time() datetime.time(12):

或只看 datetime.datetime.hour 属性

 如果dt.hour< 12 

后者更简单,前者为您提供了更多的灵活性,与包括分钟分量:

 如果dt.time()< datetime.time(12,30)

演示:

 >>> import datetime 
>>>> dt = datetime.datetime.now()
>>> dt
datetime.datetime(2014,2,10,10,39,30,768979)
>>> dt.time()< datetime.time(12)
True
>>> dt.hour 12
True
>>> dt = dt.replace(hour = 20)
>>> dt
datetime.datetime(2014,2,10,20,39,30,768979)
>>> dt.time()< datetime.time(12)
False
>>> dt.hour datetime.hour
False


I have a datetime object in python and I would like create a function to check whether the input is in the morning or afternoon on the day of the datetime (ie, before or after 12pm). How to I manually create the time 12:00 and can I use greater than or lesser than symbols for this (<, >)?

解决方案

Call the datetime.datetime.time() method on the datetime object and compare it with a datetime.time() object:

if dt.time() < datetime.time(12):

or just look at the datetime.datetime.hour attribute:

if dt.hour < 12

The latter is simpler, the former gives you more flexibility to compare against times that include a minute component:

if dt.time() < datetime.time(12, 30)

Demo:

>>> import datetime
>>> dt = datetime.datetime.now()
>>> dt
datetime.datetime(2014, 2, 10, 10, 39, 30, 768979)
>>> dt.time() < datetime.time(12)
True
>>> dt.hour < 12
True
>>> dt = dt.replace(hour=20)
>>> dt
datetime.datetime(2014, 2, 10, 20, 39, 30, 768979)
>>> dt.time() < datetime.time(12)
False
>>> dt.hour < datetime.hour
False

这篇关于如何检查日期是否在中午之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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