Home >Backend Development >Python Tutorial >Has 24 Hours Passed Since a Given DateTime in Python?
Suppose you have a datetime object called last_updated representing the last time a particular program was executed. To determine if a full 24 hours have elapsed since then, follow these steps:
import datetime now = datetime.datetime.now()
time_difference = now - last_updated
hours = time_difference.total_seconds() / 3600
if hours >= 24: # 24 hours or more have passed
Depending on whether last_updated is a naive (timezone-unaware) or timezone-aware datetime object, you may need to adjust the time difference calculation accordingly. Consult the Python documentation for more details.
For example, if last_updated is naive and represents UTC time, you can use the following code:
from datetime import datetime, timedelta if (datetime.utcnow() - last_updated) > timedelta(hours=24): # 24 hours or more have passed in UTC
If last_updated is naive and represents a local time, you can use the following code:
import time DAY = 86400 now = time.time() then = time.mktime(last_updated.timetuple()) if (now - then) > DAY: # 24 hours or more have passed in local time
For timezone-aware datetime objects, it's recommended to convert them to UTC before performing the time difference calculation.
The above is the detailed content of Has 24 Hours Passed Since a Given DateTime in Python?. For more information, please follow other related articles on the PHP Chinese website!