Created
July 11, 2016 19:40
-
-
Save emesik/81af3d3fb1b4467a817788d2e5e99bd3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import date | |
class PESEL(object): | |
"""Parses PESEL number, checks validity and extracts gender + DOB data.""" | |
gender = None | |
birth_date = None | |
pesel = None | |
def __init__(self, pesel): | |
try: | |
int(pesel) | |
except ValueError: | |
raise ValueError("PESEL must contain only digits.") | |
if len(pesel) != 11: | |
raise ValueError("PESEL must have exactly 11 digits.") | |
muls = (1,3,7,9,1,3,7,9,1,3,1) | |
chksum = 0 | |
for i in range(11): | |
chksum += int(pesel[i]) * muls[i] | |
if chksum % 10 % 10 != 0: | |
raise ValueError("Invalid checksum.") | |
y = int(pesel[:2]) | |
m = int(pesel[2:4]) | |
d = int(pesel[4:6]) | |
m2century = {80: 1800, 0: 1900, 20: 2000, 40: 2100, 60: 2200} | |
for md, cent in m2century.items(): | |
if 1 <= m - md <= 12: | |
y += cent | |
m -= md | |
break | |
try: | |
self.birth_date = date(y,m,d) | |
except ValueError: | |
raise ValueError("PESEL contains invalid birth date.") | |
self.gender = 'm' if int(pesel[9]) % 10 else 'f' | |
self.pesel = pesel |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment