Reputation: 478
We are working with Python 3, where we have a list of datetimes, which looks like this:
first_datetime = {2019-08-08 14:00:00, 2019-08-08 14:10:00, 2019-08-08 14:20:00, 2019-08-08 14:30:00, 2019-08-08 14:40:00, 2019-08-08 14:50:00, 2019-08-08 15:00:00}
What we want is to only append datetimes, where minutes in datetime is either 00, 20 or 40, into a new list.
Therefore above list should look like:
new_datetime_list = {2019-08-08 14:00:00, 2019-08-08 14:20:00, 2019-08-08 14:40:00, 2019-08-08 15:00:00}
Our program looks like following:
for i in range(len(first_datetime)):
time = datetime.datetime.strptime(first_datetime[i], '%Y-%m-%d %H:%M:%S')
if time != x:
new_datetime_list.append(first_datetime[i])
We imagine that we could do something like:
for i in range(len(first_datetime)):
time = datetime.datetime.strptime(first_datetime[i], '%Y-%m-%d %H:%M:%S')
if time != x and time != CAN'T CONTAIN 10, 30, 50 IN MINUTES:
new_datetime_list.append(first_datetime[i])
Although we dont know how to to the above, hence we are posting this post.
Upvotes: 0
Views: 66
Reputation: 4815
You can check the minutes using time.minute in [0, 20, 40]
, so your snippet of code could look like
for i in range(len(first_datetime)):
time = datetime.datetime.strptime(first_datetime[i], '%Y-%m-%d %H:%M:%S')
if time != x and time.minute in [0, 20, 40]:
new_datetime_list.append(first_datetime[i])
(I have kept the time != x
condition, not sure if you need it for something else you didn't mention)
btw you can simplify the way you iterate through the array without using indexes like this:
for str_datetime in first_datetime:
time = datetime.datetime.strptime(str_datetime, '%Y-%m-%d %H:%M:%S')
if time != x and time.minute in [0, 20, 40]:
new_datetime_list.append(str_datetime)
Upvotes: 1
Reputation: 18377
You can use the minute
operator from datetime:
import datetime
first_datetime = ['2019-08-08 14:00:00', '2019-08-08 14:10:00', '2019-08-08 14:20:00', '2019-08-08 14:30:00', '2019-08-08 14:40:00', '2019-08-08 14:50:00', '2019-08-08 15:00:00']
new_datetime_list = []
for i in first_datetime:
time = datetime.datetime.strptime(i, '%Y-%m-%d %H:%M:%S').minute
if (time == 20) | (time == 40) | (time == 0):
new_datetime_list.append(i)
Output (print(new_datetime_list)
):
['2019-08-08 14:00:00', '2019-08-08 14:20:00', '2019-08-08 14:40:00', '2019-08-08 15:00:00']
Upvotes: 0