I've spent the past hour digging around the Python docs and many SO questions; please forgive me for being another Python newbie trapped by the mystery of time difference in Python.
My goal is to determine the difference between the current time and a certain date/time regardless of being in the past/future and return a workable format such as seconds.
For example, if the inputs are 2:00PM and 4:00PM (now), I'd like it to say "-7200", representing the event occurred two hours AGO. If the inputs are Fri 4:00PM (now) and Sun 5:00PM the output should be "176400" seconds, representing two days and 1 hour from now.
Here are the things I've tried...
now = time.strftime("%a %b %d %H:%M:%S %Y")
then = time.ctime(os.path.getmtime("x.cache"))
tdelta = datetime.strptime(now, '%a %b %d %H:%M:%S %Y') - datetime.strptime(then, '%a %b %d %H:%M:%S %Y')
You should be able to use
to get the value you are looking for. This is because
tdelta is a
timedelta object, as is any difference between
A couple of notes:
strptimeis superfluous. You should be able to get the current datetime with
strptimeis more work than needed. You should be able to get the other
So, your final code could be
now = datetime.now() then = datetime.fromtimestamp(os.path.getmtime("x.cache")) tdelta = now - then seconds = tdelta.total_seconds()