I have written a simple code to check if the time difference between 2 date timestamps is more than 7 days, which comes to 604,800 seconds.
If the time in seconds is more than 604,800 then it should print "Relax you have time!!!"
Please find my code below:
import time, datetime, sys, os start_time = time.time() from datetime import datetime, timedelta, date from dateutil.parser import * datetime1="2018-07-13 03:30:00" datetime2="2018-07-20 04:30:00" datetime2=datetime.strptime(datetime2, "%Y-%m-%d %H:%M:%S").date() # this is to convert it into a datetime object datetime1=datetime.strptime(datetime1, "%Y-%m-%d %H:%M:%S").date() # this is to convert it into a datetime object difference1 =(datetime2-datetime1).total_seconds() print("the difference in seconds is "+str(difference1)) if difference1 > 604800: #if the difference is more than 7 days, relax , else start preparing print("Relax you have time!!!") else: print("You need to start preparing!!!!!")
Problem:
The code somehow calculates the time in seconds to be more than 604800 only if I change the "datetime2" to "2018-07-21" which means that it is calculating the difference in rounded-off days and not seconds and then simply converting the rounded-off days into seconds, giving the incorrect answer.
For example, in the above code, since "datetime2" is in reality away from "datetime1" by more than 604,800 seconds(to be precise it is 608,400 seconds away), the output should be "Relax you have time!!!", but we get a different output.
What have I done to solve this?
Till now I have looked at similar questions:
How do I check the difference, in seconds, between two dates? (did not work for me as I got TypeError: an integer is required (got type datetime.date))
and Time difference in seconds (as a floating point) (this caters to only very tiny time differences and does not capture a scenario when user enters timestamps himself)
and How to calculate the time interval between two time strings (this is what I have done in my code, but it does not work as expected)
Can you please suggest the problem in my code?
UPDATE: Thanks to @Tim Peters for pointing out that .date() discards the hours,mins and seconds. I only needed to discard .date() for it to work correctly.