简体   繁体   中英

How can i get the time interval in python

Now I have time : a=2015-02-23 03:56:00 b=2015-02-23 02:56:00 and many time in c how can I select the the time which are involved in this period

for d in c :

  if (a >= d>= b):

     print d

my result:

2015-02-23 13:09:00

2015-02-23 12:09:00

2015-02-23 12:09:00

the result is wrong!!!why??thanks

from datetime import datetime
start = datetime.strptime("2015-02-23 02:56:00","%Y-%m-%d %H:%M:%S")
end = datetime.strptime("2015-02-23 03:56:00","%Y-%m-%d %H:%M:%S")

if start <= d <= end:
    print(d)

I also renamed your variables to make it a little more obvious, your time needs to be >= the start time and <= the end time to be in the range.

In [1]: from datetime import datetime 
In [2]: start = datetime.strptime("2015-02-23 02:56:00","%Y-%m-%d %H:%M:%S")

In [3]: end = datetime.strptime("2015-02-23 03:56:00","%Y-%m-%d %H:%M:%S")

In [4]: d = datetime.strptime("2015-02-23 13:09:00","%Y-%m-%d %H:%M:%S")

In [5]: start <= d <= end
Out[5]: False

In [6]: d = datetime.strptime("2015-02-23 12:09:00","%Y-%m-%d %H:%M:%S")

In [7]: start <= d <= end
Out[7]: False

In [8]: d = datetime.strptime("2015-02-23 02:59:00","%Y-%m-%d %H:%M:%S")

In [9]: start <= d <= end
Out[9]: True

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