Find if 24 hrs have passed between datetimes

前端 未结 2 2076
予麋鹿
予麋鹿 2020-11-22 00:47

I have the following method:

# last_updated is a datetime() object, representing the last time this program ran
def time_diff(last_updated):
    day_period =         


        
2条回答
  •  闹比i
    闹比i (楼主)
    2020-11-22 01:30

    Just to clear our some things, because I don't think all of us make use of the time Python lib. When you use datetime, which is especially in Django a very common practice, if you do the comparison like this:

    if (now - then) > DAY:
    

    it will hugely fail. This is because you can't compare datetime.timedelta to int.

    The solution to this is to convert your objects to seconds.
    For example:

    from datetime import datetime
    
    then = datetime_object
    now = datetime.now()
    
    if (now - then).total_seconds() > NUMBER_OF_SECONDS:
        # do something
    

    Hope I helped out whoever faced issues on that.
    Cheers

提交回复
热议问题