Let's say x and y are开发者_C百科 datetime objects in Python.
How do I check:
if y - x is more than 30 seconds:
print "ok, 30 seconds have passed"
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):
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
Use a timedelta to compare the two dates - it will let you test how many seconds are between them.
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
.
精彩评论