简体   繁体   中英

how to check if date is in certain interval python?

I'm importing dates from yahoo finance and want to transform them in a format so that I can compare them with today to check if the date is between 3 and 9 months from now.

Here is what I have so far:

today = time.strftime("%Y-%m-%d")
today = datetime.datetime.strptime(today, '%Y-%m-%d')
int_begin = today + datetime.timedelta(days=90)
int_end = today + datetime.timedelta(days=270)

for i in opt["Expiry"]:
    transf_date = datetime.datetime.strptime(opt["Expiry"][1],'%b %d, %Y')
    transf_date = datetime.datetime.strftime(transf_date,"%Y-%m-%d")
    if int_begin <= transf_date and transf_date <= int_end:
        print "True:",i
    else:
        print "False:",i

Here is the content of opt["Expiry"]

0      Jan 20, 2017
1      Jan 20, 2017
2      Jan 20, 2017
3      Jan 20, 2017
4      Jan 20, 2017
5      Jan 20, 2017
6      Jan 20, 2017
7      Jan 20, 2017
8      Jan 20, 2017
9      Jan 20, 2017
10     Jan 20, 2017
11     Jan 20, 2017
12     Jan 20, 2017
13     Jan 20, 2017
14     Jan 20, 2017
15     Jan 20, 2017
16     Jan 20, 2017
17     Jan 19, 2018
18     Jan 20, 2017
19     Jan 19, 2018
20     Jan 20, 2017
21     Mar 17, 2017
22     Jan 20, 2017
23     Mar 17, 2017
24     Jan 20, 2017
25     Mar 17, 2017
26     Apr 21, 2017
27     Jun 16, 2017
28     Jan 19, 2018
29     Jan 20, 2017
           ...     
432    Jan 20, 2017
433    Jan 19, 2018
434    Oct 21, 2016
435    Jan 20, 2017
436    Jan 19, 2018
437    Oct 21, 2016
438    Jan 20, 2017
439    Jan 19, 2018
440    Oct 21, 2016
441    Jan 20, 2017
442    Jan 19, 2018
443    Oct 21, 2016
444    Jan 20, 2017
445    Jan 19, 2018
446    Oct 21, 2016
447    Jan 20, 2017
448    Oct 21, 2016
449    Jan 20, 2017
450    Oct 21, 2016
451    Jan 20, 2017
452    Oct 21, 2016
453    Jan 20, 2017
454    Oct 21, 2016
455    Jan 20, 2017
456    Oct 21, 2016
457    Jan 20, 2017
458    Jan 20, 2017
459    Jan 20, 2017
460    Jan 20, 2017
461    Jan 20, 2017

It seems like I have the same date format, which is "%Y-%m-%d", but I still get no values filtered out. All of them come out as true, being inside the interval.

您正在使用transf_date = datetime.datetime.strptime(opt["Expiry"][1],'%b %d, %Y')而不是transf_date = datetime.datetime.strptime(opt["Expiry"][i],'%b %d, %Y') ,这意味着即使您遍历整个opt["Expiry"] ,也始终会处理相同的条目。

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