I am facing weird Python Date Time Comparison issue. I am getting two date times in string format (From REST Call, JSON) start date time and end date time. I have to compare current date time and if it falls within this rage (start date time and end date time) take some action. It is known that the time zone of these dates is US/Eastern (USA North Carolina). Here is the code,
from pytz import timezone
from datetime import datetime
def main():
# All the dates are in US/Eastern time zone. Time zone for USA, North Carolina
# These dates are received from REST call in JSON
# I need to compare the current date time, if that falls within this range take some action
start_date_str = "7/17/2018 11:30:00 AM"
end_date_str = "7/17/2018 2:30:00 PM"
# To simulate current date time within the range, I will update the current date time value.
current_est_time = datetime.now(tz=timezone('US/Eastern'))
current_est_time = current_est_time.replace(year=2018, month=7, day=17, hour=12, minute=26)
print current_est_time
start_date = datetime.strptime(start_date_str,"%m/%d/%Y %I:%M:%S %p").replace(tzinfo=timezone('US/Eastern'))
end_date = datetime.strptime(end_date_str, "%m/%d/%Y %I:%M:%S %p").replace(tzinfo=timezone('US/Eastern'))
print start_date <= current_est_time <= end_date
if __name__ == '__main__':
main()
If minute value is 26, comparison prints True, if it is 25, it prints False.
Output of the above code sample is
2018-07-17 12:26:06.646643-04:00
True
If you change the minute value for current_est_time variable to 25, output is
2018-07-17 12:25:16.582573-04:00
False
Can somebody please help me, where I am going wrong here ?