Search code examples
python-2.7datetimecronclosesthour

Pick closest hour from a list, based on current time with script running on Cron schedule


I have an AWS Lambda Python script that is invoked by an AWS Cloudwatch Events Rule (cron-like) at certain times of the day (see list below). The script is invoked but has no idea what time it was invoked, so that logic needs to be in code and that's OK.

However, I want to account for the fact that there could be an occasional latency or time-blip that changes exactly when the script runs (difference could be ms, sec, or min - negative or positive).

I've tried some combinations of datetime, timedelta, strptime, and time. I've tried calculating time differences and find the one with the least difference, but negative differences proved problematic.

Here's my list:

hours_we_run_utc = [ '01:00', '07:00', '13:00', '15:00', '20:00' ]

curr_time = datetime.datetime.utcnow() #when Lambda/script was invoked.

What I need:

If curr_time, for example, is 00:59:99 or 00:59:30 or even 00:58:00, then the script must assume it was run at 01:00.

If curr_time, for example, is 01:00:01 or 01:01:00 or even 01:03:05, then the script must assume it was run at 01:00.


Solution

  • Replacing the if with an abs call and tdelta.total_seconds() for a unique value tightens up your solution.

    from datetime import datetime
    
    t_dict={}
    hours_we_run_utc = [ '01:00', '07:00', '13:00', '15:00', '20:00' ]
    FMT='%H:%M'
    
    for hour in hours_we_run_utc:
      s1 = datetime.utcnow().strftime(FMT) #Get current time
      s2 = str(hour)
      tdelta = abs(datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT))
      t_dict[tdelta.total_seconds()] = hour
    
    print t_dict[sorted(t_dict)[0]]