开发者

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

开发者 https://www.devze.com 2023-01-30 19:27 出处:网络
Let\'s say x and y are开发者_C百科 datetime objects in Python. How do I check: if y - x is more than 30 seconds:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消