Skip to main content
 首页 » 编程设计

python之如何检查时间值

2025年05月04日17davidwang456

我想知道给定的时间是上午还是下午。我不确定这是否是在 python 中创建 Time 对象并进行比较的正确方法。或者有更好的方法吗?

def part_of_day_statistics(x): 
    if x > time.strptime('6:00 am') and x < time.strptime('11:59 am'): 
        return 'Morning'  
    if x > time.strptime('12:00 pm') and x < time.strptime('5:59 pm'): 
        return 'Afternoon'  

请您参考如下方法:

Django TimeField entries是datetime.time instances ,它有一个 .hour 属性(范围从 0 到 23):

def part_of_day_statistics(x): 
    if x.hour >= 6 and x.hour < 12: 
        return 'Morning' 
    if x.hour >= 12 and x.hour < 18: 
        return 'Afternoon'