Arthur de Jong

Open Source / Free Software developer

summaryrefslogtreecommitdiffstats
path: root/stdnum/se/personnummer.py
blob: fc8f3457cf0a30bbe51317e1abe9f4f8d7bc498e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
# personnummer.py - functions for handling Swedish Personal identity numbers
# coding: utf-8
#
# Copyright (C) 2018 Ilya Vihtinsky
# Copyright (C) 2018 Arthur de Jong
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301 USA

"""Personnummer (Swedish personal identity number).

The Swedish Personnummer is assigned at birth to all Swedish nationals and to
immigrants for tax and identification purposes. The number consists of 10 or
12 digits and starts with the birth date, followed by a serial and a check
digit.

More information:

* https://en.wikipedia.org/wiki/Personal_identity_number_(Sweden)

>>> validate('880320-0016')
'8803200016'
>>> validate('880320-0018')
Traceback (most recent call last):
    ...
InvalidChecksum: ...
>>> get_gender('890102-3286')
'F'
>>> get_birth_date('811228-9841')
datetime.date(1981, 12, 28)
>>> format('8803200016')
'880320-0016'
"""

import datetime

from stdnum import luhn
from stdnum.exceptions import *
from stdnum.util import clean


def compact(number):
    """Convert the number to the minimal representation. This strips the
    number of any valid separators and removes surrounding whitespace."""
    return clean(number, ' -+:')


def get_birth_date(number):
    """Guess the birth date from the number.

    Note that it may be 100 years off because the number has only the last
    two digits of the year."""
    number = compact(number)
    if len(number) == 12:
        year = int(number[0:4])
        month = int(number[4:6])
        day = int(number[6:8])
    else:
        year = datetime.date.today().year
        year = year - (year - int(number[0:2])) % 100
        month = int(number[2:4])
        day = int(number[4:6])
    try:
        return datetime.date(year, month, day)
    except ValueError:
        raise InvalidComponent()


def get_gender(number):
    """Get the person's birth gender ('M' or 'F')."""
    number = compact(number)
    if int(number[-2]) % 2:
        return 'M'
    else:
        return 'F'


def validate(number):
    """Check if the number is a valid identity number."""
    number = compact(number)
    if len(number) not in (10, 12):
        raise InvalidLength()
    if not number.isdigit():
        raise InvalidFormat()
    get_birth_date(number)
    luhn.validate(number[-10:])
    return number


def is_valid(number):
    """Check if the number is a valid identity number."""
    try:
        return bool(validate(number))
    except ValidationError:
        return False


def format(number):
    """Reformat the number to the standard presentation format."""
    number = compact(number)
    return number[:6] + '-' + number[6:]