Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to find if 24 hrs have passed between datetimes in Python?
To determine if 24 hours have passed between two datetimes in Python, you need to calculate the time difference and compare it to a 24-hour duration. The datetime module provides tools to perform this calculation using timedelta objects.
Basic Approach Using total_seconds()
Subtract two datetime objects to get a timedelta, then use total_seconds() to compare with 24 hours in seconds ?
from datetime import datetime
NUMBER_OF_SECONDS = 86400 # seconds in 24 hours
first = datetime(2017, 10, 10)
second = datetime(2017, 10, 12)
if abs((second - first).total_seconds()) > NUMBER_OF_SECONDS:
print("It's been over a day!")
else:
print("Less than 24 hours have passed")
It's been over a day!
Using timedelta for Direct Comparison
You can also create a timedelta object representing 24 hours and compare directly ?
from datetime import datetime, timedelta
first = datetime(2023, 5, 15, 10, 30)
second = datetime(2023, 5, 16, 15, 45)
time_difference = abs(second - first)
twenty_four_hours = timedelta(hours=24)
if time_difference > twenty_four_hours:
print(f"More than 24 hours: {time_difference}")
else:
print(f"Less than 24 hours: {time_difference}")
More than 24 hours: 1 day, 5:15:00
Practical Example with Current Time
Check if a specific datetime is more than 24 hours ago from now ?
from datetime import datetime, timedelta
# Some past datetime
past_time = datetime(2023, 5, 15, 14, 30)
current_time = datetime.now()
# Replace current_time with a known value for demonstration
current_time = datetime(2023, 5, 17, 10, 15)
time_elapsed = current_time - past_time
if time_elapsed > timedelta(days=1):
print(f"More than 24 hours ago: {time_elapsed}")
else:
print(f"Within last 24 hours: {time_elapsed}")
More than 24 hours ago: 1 day, 19:45:00
Comparison of Methods
| Method | Readability | Best For |
|---|---|---|
total_seconds() |
Good | When working with seconds |
timedelta comparison |
Better | Direct time unit comparison |
timedelta(days=1) |
Best | Most readable for day comparison |
Conclusion
Use timedelta(days=1) for the most readable approach when checking if 24 hours have passed. Remember to use abs() if you want to check the absolute difference regardless of which datetime is larger.
Advertisements
