Using Rouble's suggestion and Maulik Gangani's example based on that suggestion:
How do I determine if current time is within a specified range using Python's datetime module?
I have two time strings that have been converted into a datetime object using .strptime as follows:
timeStart = '0300'
timeStart = datetime.strptime(timeStart, '%H%M')
I have a datetime object for time now: timeNow = datetime.now()
My problem is that unless I convert timeNow (datetime object) into a string and then back again using .strptime , the script will not work:
timeNow = datetime.now()
timeNow = datetime.strftime(timeNow, '%H%M')
timeNow = datetime.strptime(timeNow, '%H%M')
Full code:
from datetime import datetime
def isNowInTimePeriod(startTime, endTime, nowTime):
if startTime < endTime:
return nowTime >= startTime and nowTime <= endTime
else: #Over midnight
return nowTime >= startTime or nowTime <= endTime
timeStart = '0300'
timeEnd = '1000'
timeEnd = datetime.strptime(timeEnd, '%H%M')
timeStart = datetime.strptime(timeStart, '%H%M')
timeNow = datetime.now()
timeNow = datetime.strftime(timeNow, '%H%M')
timeNow = datetime.strptime(timeNow, '%H%M')
My question is, how do I format timeNow = datetime.now() so that I can compare it against a string in 24hr format '0000' without having to convert datetime.now() to a string and back again?