简体   繁体   中英

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"

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

使用timedelta比较两个日期-它可以让您测试两个日期之间的秒数。

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM