Question

My application needs to compare the difference between two unix timestamps and return True or False. In summary, if the user has rated within a day or week of an attempted rating the function returns false. I fear this may not be very pythonic and that I may have re-invented the wheel. Is there a pre-packaged library in python 2.5 that will help me reach this same result in a better way?

import time

def is_allowed(time_rated, duration):
    durations={'day': 86400, 'week': 604800}
    if duration in durations and isinstance(time_rated, int):
        time_difference = int(time.time()) - time_rated
        if  time_difference > durations[duration]:
            return True
        else:
            return False
    return False
Was it helpful?

Solution

No, you are doing fine here, but you can just return the result of the > comparison, it already gives you a boolean value. There is also no need to turn the time.time() float to an integer here:

def is_allowed(time_rated, duration):
    durations = {'day': 86400, 'week': 604800}
    if duration in durations and isinstance(time_rated, int):
        time_difference = time.time() - time_rated
        return time_rated > durations[duration]
    return False

You can simplify this further by defaulting to a duration of float('inf'), saving you an if test:

def is_allowed(time_rated, duration):
    if not isinstance(time_rated, int):
        return False
    duration = {'day': 86400, 'week': 604800}.get(duration, float('inf'))
    return time.time() - time_rated > duration

This returns False if:

  • time_rated is not an integer
  • duration is not equal to 'day' or 'week' (because no number is ever greater than float('inf')).
  • time_rated is less than 86400 or 604800 seconds ago, depending on duration.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top