在Python中创建小时数 [英] Create Range of Hours in Python

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

问题描述

所以我正在等待7:00 AM的输入作为开始时间,并说10:00 PM作为结束时间,然后比较一组时间(也以8:00 AM的形式) ,下午3:00等),看看这些时间是否在时间范围内。有没有一个很好的方式来创建一个有一小段时间的一天(终点可以晚到凌晨4点,所以我想我会从上午6:00到上午5:59而不是午夜 - 11:59 PM,如果可以的话)我可以检查时间?

So I'm looking to take input such as 7:00 AM as a start time, and say, 10:00 PM as an endtime, and then compare a set of times (also in the form of 8:00 AM, 3:00 PM, etc) to see if those time are or aren't in the range of time. Is there a good way to create a "day" that has a range of hours (the endtimes can be as late as 4:00 AM, so I was figuring I would go from 6:00 AM - 5:59 AM instead of midnight - 11:59 PM, if that's possible) that I can check times against?

例如: starttime = 8:00 AM,endtime = 3:00 AM ,并检查 time = 7:00 AM 将返回时间超出范围。

For example: starttime = 8:00 AM, endtime = 3:00 AM, and checking time = 7:00 AM would return time as being out of the range.

谢谢!

推荐答案

使用 datetime 解析和比较功能:

Use datetime parsing and comparison capabilities:

from datetime import datetime, timedelta

def parse_time(s):
    ''' Parse 12-hours format '''
    return datetime.strptime(s, '%I:%M %p')

starttime = parse_time('8:00 AM')
endtime   = parse_time('3:00 AM')
if endtime < starttime:
   # add 1 day to the end so that it's after start
   endtime += timedelta(days=1)

checked_time = parse_time('7:00 AM')

# Can compare:
print starttime <= checked_time < endtime

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

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