Feb-12-2020, 08:44 AM
Hi,
I have started learning Python not far ago. I have a program that search for dates in a string (this part works ok) and than checks date correctness (e.g. February cannot have 30 days). I know that there is modul datetime but I wanted to check myself and do it on my own. Please note, that February has 29 days in leap years. Leap years are every year evenly divisible by 4, except for years evenly divisible by 100, unless the year is also evenly divisible by 400.
[['30', '02', '2000'], ['29', '02', '2000'], ['30', '02', '2100'], ['29', '02', '2100'], ['31', '02', '2004'], ['30', '02', '2004'], ['29', '02', '2004']]
['30', '02', '2000']
['30', '02', '2100']
['31', '02', '2004']
['29', '02', '2004']
[['29', '02', '2000'], ['29', '02', '2100'], ['30', '02', '2004'], ['29', '02', '2004']]
List dates is correct (7 elements), but for loop has only four elements (I add additional print, because I got confused). Final result is a list with 4 different dates (but it has mistakes e.g. ['30', '02', '2004']). What did I wrong?
I have started learning Python not far ago. I have a program that search for dates in a string (this part works ok) and than checks date correctness (e.g. February cannot have 30 days). I know that there is modul datetime but I wanted to check myself and do it on my own. Please note, that February has 29 days in leap years. Leap years are every year evenly divisible by 4, except for years evenly divisible by 100, unless the year is also evenly divisible by 400.
import re dates = [] eachDate = [] text = '30/02/2000, 29/02/2000, 30/02/2100, 29/02/2100, 31/02/2004, 30/02/2004, 29/02/2004' dateRegex = re.compile(r'''( (0\d|1\d|2\d|30|31) #day (/) (0\d|10|11|12) #month (/) (1\d\d\d|2\d\d\d) )''', re.VERBOSE) for groups in dateRegex.findall(text): eachDate = [] eachDate.append(groups[1]) eachDate.append(groups[3]) eachDate.append(groups[5]) dates.append(eachDate) print(dates) for item in dates: print(item) if item[1] in ('04', '06', '09', '11'): if item[0] == '31': dates.remove(item) elif item[1] == '02': if item[0] == '30': dates.remove(item) elif item[0] == '31': dates.remove(item) elif item[0] == '29': if int(item[2]) % 400 == 0: continue elif int(item[2]) % 100 == 0: dates.remove(item) elif int(item[2]) % 4 == 0: continue else: dates.remove(item) print(dates)results:
[['30', '02', '2000'], ['29', '02', '2000'], ['30', '02', '2100'], ['29', '02', '2100'], ['31', '02', '2004'], ['30', '02', '2004'], ['29', '02', '2004']]
['30', '02', '2000']
['30', '02', '2100']
['31', '02', '2004']
['29', '02', '2004']
[['29', '02', '2000'], ['29', '02', '2100'], ['30', '02', '2004'], ['29', '02', '2004']]
List dates is correct (7 elements), but for loop has only four elements (I add additional print, because I got confused). Final result is a list with 4 different dates (but it has mistakes e.g. ['30', '02', '2004']). What did I wrong?