Home > Software design >  Select only 10 first minutes of each hour of a datetime list
Select only 10 first minutes of each hour of a datetime list

Time:01-31

I have a datetime list that looks like this, which contains every timestamp with approximately 125ms between each timestamp, between the 6th and the 14th and the 21th of june in 2019:

[datetime.datetime(2019, 6, 14, 14, 8, 23, 493000)
 datetime.datetime(2019, 6, 14, 14, 8, 23, 618000)
...
 datetime.datetime(2019, 6, 21, 20, 45, 23, 868000)
 datetime.datetime(2019, 6, 21, 20, 45, 23, 993000)]

And I want to have a new list containing the same data but keeping only the 10 first minutes of each hour. For example, my list will contain datetime.datetime(2019, 6, 14, 14, 8, 23, 493000) because it is at minute 8, but not the timestamp datetime.datetime(2019, 6, 14, 14, 25, 23, 493000) because it is at minute 25. Given that the 125ms difference between each timestamp is not regular in the dataset, how would you filter the list like that ? I was thinking of transforming my list into n lists, with each list containing the datetimes of each hour of each day, then sorting every list from the lowest datetime to the highest for each hour, then finding the timestamp where minutes is above 10, and then selecting the index i of that element to select only values [0,i] for each list. This seems very tidious and not very efficient. Is there a faster and better way that I'm missing ?

CodePudding user response:

you can get any datetime object part with .year / .minute etc so:


dt_list = [datetime.datetime(2019, 6, 14, 14, 8, 23, 493000),
 datetime.datetime(2019, 6, 14, 14, 14, 23, 618000)]

output = [dt for dt in dt_list if dt.minute < 11]

will output:

[datetime.datetime(2019, 6, 14, 14, 8, 23, 493000)]
  • Related