python - 如何检查时间值?

标签 python django time

我想知道给定的时间是上午还是下午。我不确定这是否是在 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 entriesdatetime.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'

关于python - 如何检查时间值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11810106/

相关文章:

mysql - 如何在 Django 中测试数据库中的空字符串?

css - Django 只应用我的 css 文件中的第一个样式

python - 测量 Jupyter Notebook 代码单元的运行时间

python - 在 Pandas DataFrame 之间匹配 ID 并应用函数

python - sqlalchemy.orm.exc.UnmappedInstanceError : Class 'builtins.dict' is not mapped

python - 如何更改 Django 电子邮件中的发件人地址?

python-2.7 - 用于 python 的 TSFRESH 库处理时间太长

计算C中2个给定日期之间的随机日期

python - 在 python 中嵌入 for 循环

python - 如何从 Unix 时间戳中删除小时、分钟和秒?