Reputation: 479
Lets take the next reproducible example:
I have a numpy array with a sequence of datetime.datetime
elements in an hourly frequency,
From that array, I want to create a list datesVect
which I want to be True for datetimes
between Februrary and April and else False.
following the validated answer of this question and the explanation of the usage of list comprehension conditionals of this post I try to do it with the following code:
import numpy as np
import datetime
#Setting the startdate and creating the data range array:
startDate = datetime.datetime(2023,1,1)
dateHour = np.array([startDate + datetime.timedelta(0,3600*n) for n in range(8760)])
#Creating the desired list
datesVect = [True if j.month < 5 else True if j.month > 1 else False for j in dateHour]
Instead of getting the desired result I get a list full of True
values:
In [211]: all(datesVect)
Out[211]: True
Anyone knows why I don't get the desired result?
Upvotes: 0
Views: 65
Reputation: 442
I recommend to just use the and
operator. Your current code is functioning similar to the or
operator, hence why you get an array of all True values. To be between Feb and April the month must be greater than 1 and less than 5.
datesVect = [True if (j.month < 5 and j.month > 1) else False for j in dateHour]
Upvotes: 1