Reputation: 1160
import datetime
random_list = ["lol", "2020-10-05", "2020-09-11"]
date_list = []
for item in random_list:
try:
date = datetime.datetime.strptime(item, "%Y-%m-%d")
date_list.append(date)
except ValueError:
print("Not a valid date foramt")
print(date_list)
In the above code, I am basically passing through some random_list
and if i see a string that is of valid date format i want to add it another list called date_list
.
I only want to add strings that are of valid date format meaning if i see a random string "foo" i want to ignore it and not append it to the date_list
.
I guess what would be the best and most pythonic way to handle this?
Ideally if there were some boolean function that would tell me if the string i am looking at is a date then i would be able to just append strings to date_list
when they return True upon validation.
I would love some thoughts on the correct way i can handle this.
Upvotes: 0
Views: 139
Reputation: 948
Well, as you are using the specific format YYYY-MM-DD you can trivially do it via regular expressions. Something like this:
import re
import datetime
rDate = re.compile(r'^\d\d\d\d-\d\d-\d\d$')
isDate = lambda d: rDate.match(d)
toDate = lambda d: datetime.datetime.strptime(d, "%Y-%m-%d")
random_list = ["lol", "2020-10-05", "2020-09-11"]
date_list = list(map(toDate, filter(isDate, random_list)))
print(date_list)
I get this result:
$ /bin/python ./dates.py
[datetime.datetime(2020, 10, 5, 0, 0), datetime.datetime(2020, 9, 11, 0, 0)]
Upvotes: 1
Reputation: 2607
thats a pretty good way to do it, you could implement it using a list comprehension or using the filter
function
random_list = ["lol", "2020-10-05", "2020-09-11"]
def validate(date_text):
try: datetime.datetime.strptime(date_text, '%Y-%m-%d'); return True
except ValueError: return False
random_list = list(filter(validate, random_list))
print(random_list)
#or
[i for i in random_list if validate(i)]
both will give you:
["2020-10-05", "2020-09-11"]
if you want to convert its easiest to use the list comprehension with filter
[datetime.datetime.strptime(i, '%Y-%m-%d') for i in list(filter(validate, random_list))]
[datetime.datetime(2020, 10, 5, 0, 0), datetime.datetime(2020, 9, 11, 0, 0)]
Upvotes: 1