Wednesday, October 27, 2021

[SOLVED] python subtract time and run if loop

Issue

I want to compare two times and if the new time is more than 2min then the if statement will print output, I can get the output of datetime.datetime.now() , but how do I check whether the old time is less than 2mins?

#!/usr/bin/env python


import datetime
from time import sleep
now = datetime.datetime.now()

sleep(2)

late = datetime.datetime.now()
constant = 2
diff = late-now
if diff <= constant:
    print "True time is less than 2min"
else:
    print "Time exceeds 2 mins"

any ideas?

UPDATED:

I am now storing the old date as string in file and then subtract it from current time, the old date is stored in the format

2011-12-16 16:14:50.800856

so when I do

now = "2011-12-16 16:14:50.838638"

sleep(2)

nnow = datetime.strptime(now, '%Y-%m-%d %H:%M:%S')

late = datetime.now()

diff = late-nnow

it gives me this error

ValueError: unconverted data remains: .838638

Solution

Subtracting two datetime instances returns a timedelta that has a total_seconds method:

contant = 2 * 60
diff = late-now
if diff.total_seconds() <= constant:


Answered By - sje397