TIMEX
TIMEX

Reputation: 271774

How do I check the difference in time of 2 datetime objects?

Let's say x and y are datetime objects in Python.

How do I check:

if y - x is more than 30 seconds:
    print "ok, 30 seconds have passed"

Upvotes: 3

Views: 3389

Answers (4)

gahooa
gahooa

Reputation: 137302

Subtracting two datetime objects will produce a datetime.timedelta object.

These objects have a convenient attribute, seconds, which gives the number of seconds contained in the timedelta.

Upvotes: 0

sje397
sje397

Reputation: 41822

For Python 2.7 you can do:

if (y - x).total_seconds() > 30:
  print "ok, 30 seconds have passed"

or this should work:

if y - datetime.timedelta(seconds = 30) > x:
  print "ok, 30 seconds have passed"

Ref: timedelta

Upvotes: 3

girasquid
girasquid

Reputation: 15516

Use a timedelta to compare the two dates - it will let you test how many seconds are between them.

Upvotes: 0

THE DOCTOR
THE DOCTOR

Reputation: 4555

The following class can be used for duration expressing the difference between two date, time, or datetime instances to microsecond resolution:

class datetime.timedelta

The following code can be used for your purposes:

if (y-x) >datetime.timedelta(0,30):

Upvotes: 5

Related Questions