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

DateCleaner.clean()   F

Complexity

Conditions 17

Size

Total Lines 35

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 15
CRAP Score 17

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 35
ccs 15
cts 15
cp 1
rs 2.7204
cc 17
crap 17

How to fix   Complexity   

Complexity

Complex classes like DateCleaner.clean() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

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