Completed
Push — master ( 011702...a4103f )
by P.R.
01:44
created

DateCleaner   A

Complexity

Total Complexity 17

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 17
c 1
b 0
f 0
dl 0
loc 41
ccs 16
cts 16
cp 1
rs 10

1 Method

Rating   Name   Duplication   Size   Complexity  
F clean() 0 35 17
1
"""
2
ETLT
3
4
Copyright 2016 Set Based IT Consultancy
5
6
Licence MIT
7
"""
8 1
import re
9
10
11 1
class DateCleaner:
12
    """
13
    Utility class for converting dates in miscellaneous formats to ISO-8601 (YYYY-MM-DD) format.
14
    """
15
16
    # ------------------------------------------------------------------------------------------------------------------
17 1
    @staticmethod
18
    def clean(date):
19
        """
20
        Converts a date in miscellaneous format to ISO-8601 (YYYY-MM-DD) format.
21
22
        :param str date: The input date.
23
        :rtype str:
24
        """
25
        # Return empty input immediately.
26 1
        if not date:
27 1
            return date
28
29 1
        parts = re.split(r'[\-/\. ]', date)
30
31 1
        if len(parts) == 3 or (len(parts) == 4 and (parts[3] in ('00:00:00', '0:00:00'))):
32 1
            if len(parts[0]) == 4 and len(parts[1]) <= 2 and len(parts[2]) <= 2:
33
                # Assume date is in  YYYY-MM-DD of YYYY-M-D format.
34 1
                return parts[0] + '-' + ('00' + parts[1])[-2:] + '-' + ('00' + parts[2])[-2:]
35
36 1
            if len(parts[0]) <= 2 and len(parts[1]) <= 2 and len(parts[2]) == 4:
37
                # Assume date is in  DD-MM-YYYY or D-M-YYYY format.
38 1
                return parts[2] + '-' + ('00' + parts[1])[-2:] + '-' + ('00' + parts[0])[-2:]
39
40 1
            if len(parts[0]) <= 2 and len(parts[1]) <= 2 and len(parts[2]) == 2:
41
                # Assume date is in  DD-MM-YY or D-M-YY format.
42 1
                year = '19' + parts[2] if parts[2] >= '20' else '20' + parts[2]
43
44 1
                return year + '-' + ('00' + parts[1])[-2:] + '-' + ('00' + parts[0])[-2:]
45
46 1
        if len(parts) == 1 and len(date) == 8:
47
            # Assume date is in YYYYMMDD format.
48 1
            return date[0:4] + '-' + date[4:6] + '-' + date[6:8]
49
50
        # Format not recognized. Just return the original string.
51 1
        return date
52
53
# ----------------------------------------------------------------------------------------------------------------------
54