Reputation: 129
I have this list of dates:
['2020-03-17 12:00:00', '2020-03-17 15:00:00', '2020-03-17 18:00:00', '2020-03-17 21:00:00', '2020-03-18 00:00:00', '2020-03-18 03:00:00', '2020-03-18 06:00:00', '2020-03-18 09:00:00', '2020-03-18 12:00:00', '2020-03-18 15:00:00', '2020-03-18 18:00:00', '2020-03-18 21:00:00', '2020-03-19 00:00:00', '2020-03-19 03:00:00', '2020-03-19 06:00:00', '2020-03-19 09:00:00', '2020-03-19 12:00:00', '2020-03-19 15:00:00', '2020-03-19 18:00:00', '2020-03-19 21:00:00']
It contains times with a 3 hour gap each and several dates upto 2020-3-19, in the format of YYYY-MM-DD HH-MM-SS.
Using date i can get today's date, and now i want to compare today's date to my list above and get all the dates that match today's current date and tommorow, i.e: Today is 2020-03-17, i want to get all dates with their times that match today and tommorow's date, meaning 2020-03-17 and 2020-03-18
from datetime import date
current_date = date.today()
This is for a small practice project in python for a weather api request. (I'm new to the python, i tried researching about this issue, it's quite hard to get results and it would be best to ask it here, might be a waste of time for you guys but it helps greatly~)
Thanks!
Upvotes: 0
Views: 341
Reputation: 3503
Using dateutil.parser
helps you avoid defining/handling a fixed datetime format. It handles that automatically for you.
from dateutil import parser
from datetime import date, timedelta
#timestamps=[your list of datatimes]
today = date.today()
tomorrow=today + timedelta(days=1)
result=[dt for dt in timestamps if today <= parser.parse(dt).date() <= tomorrow]
Upvotes: 0
Reputation: 36339
You can loop over the array and check whether the dates are current to today or tomorrow's date object:
from datetime import datetime, timedelta
today = datetime.now().date()
tomorrow = today + timedelta(days=1)
dates = [datetime.strptime(s, '%Y-%m-%d %H:%M:%S').date() for s in strings]
result = [date for date in dates if date in (today, tomorrow)]
Upvotes: 1
Reputation: 88305
You could define today and tomorrow's date beforehand, loop over the strings in the list, parse them appropiately using datetime.strptime
, and see if the date part matches with either today or tomorrow's date:
from datetime import datetime, timedelta
today = datetime.today().date()
tomorrow = today + timedelta(days=1)
out = []
for i in l:
date = datetime.strptime(i, '%Y-%m-%d %H:%M:%S').date()
if date == today or date == tomorrow:
out.append(i)
print(out)
['2020-03-17 12:00:00',
'2020-03-17 15:00:00',
'2020-03-17 18:00:00',
'2020-03-17 21:00:00',
'2020-03-18 00:00:00',
'2020-03-18 03:00:00',
'2020-03-18 06:00:00',
'2020-03-18 09:00:00',
'2020-03-18 12:00:00',
'2020-03-18 15:00:00',
'2020-03-18 18:00:00',
'2020-03-18 21:00:00']
Upvotes: 2