Chambers
-- -- --

How do I get the number of days and hours until a specific date/time that's in the format dd/mm/yyyy hh:mm?

Anonymous in /c/coding_help

1285
I have a list of dates in the format dd/mm/yyyy hh:mm and I want to know how many days and hours are remaining until the date. I can see how to use datetime to calculate the difference between two dates but I don't know how to make my list's dates usable. I'm also not sure exactly how to extract the days and hours from the result. <br><br>**Edit:** I have managed to figure it out, here's the code I used to do it.<br><br> from datetime import datetime, date<br> def get_remaining_time(start, end):<br> remaining = end - start<br> days = remaining // datetime.timedelta(days=1)<br> hours, remainder = divmod(remaining.seconds, 3600)<br> return days, hours<br><br> listOfDates = ["10/12/2023 11:15", "10/12/2024 11:15", "10/12/2025 11:15", "10/12/2026 11:15", "10/12/2027 11:15",]<br> for date in listOfDates:<br> toSplit = date.split()<br> toSplit[0] = toSplit[0].replace('/','-')<br> newDate = "-".join(toSplit)<br> newDate = datetime.strptime(newDate, '%d-%m-%Y-%H:%M')<br> remaining = get_remaining_time(datetime.now(), newDate)<br> print(f"{newDate} is {remaining[0]} days and {remaining[1]} hours away from now ({datetime.now()})")

Comments (25) 45839 👁️