-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreformat_date.py
More file actions
45 lines (35 loc) · 1.29 KB
/
reformat_date.py
File metadata and controls
45 lines (35 loc) · 1.29 KB
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
"""
Module to convert an array of dates into ISO format.
Author: Alexander Scheibler
"""
import datetime
import re
def reformat_date(dates):
"""
Converts an array of dates to ISO format.
Ex: '26th Dec 2061' to '2061-12-26'.
args:
dates: array of dates in the format %d-%b-%Y
"""
reformated_dates = []
for item in dates:
# Check type explicitly
if not isinstance(item, str):
raise TypeError(f'Expected string, got {type(item).__name__}')
# Fix Whitespace
item = item.strip()
day, month, year = item.split(' ')
day_numbers = re.compile(r'\d+')
# Fix wrong patterns such as '23rdx'
suffix = re.sub(r'\d+', '', day)
if suffix not in ('st', 'nd', 'rd', 'th'):
raise ValueError(f"Invalid day suffix: '{suffix}'")
day = day_numbers.findall(day)[0]
formatted_date = datetime.datetime.strptime(f'{year}-{month}-{day}',
'%Y-%b-%d')
reformated_dates.append(
datetime.date(formatted_date.year,
formatted_date.month,
formatted_date.day).isoformat())
return reformated_dates
print(reformat_date(['25th May 1912', '16th Dec 2018', '26th Dec 2061']))