-
-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathrecipes.py
More file actions
76 lines (67 loc) · 2.01 KB
/
recipes.py
File metadata and controls
76 lines (67 loc) · 2.01 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
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
from __future__ import annotations
from typing import Callable, Optional
from dateutil import parser
import json
IGNORE: object = object()
SET_NULL: object = object()
def parsedate(
value: str,
dayfirst: bool = False,
yearfirst: bool = False,
errors: Optional[object] = None,
) -> Optional[str]:
"""
Parse a date and convert it to ISO date format: yyyy-mm-dd
\b
- dayfirst=True: treat xx as the day in xx/yy/zz
- yearfirst=True: treat xx as the year in xx/yy/zz
- errors=r.IGNORE to ignore values that cannot be parsed
- errors=r.SET_NULL to set values that cannot be parsed to null
"""
if not value:
return value
try:
return (
parser.parse(value, dayfirst=dayfirst, yearfirst=yearfirst)
.date()
.isoformat()
)
except parser.ParserError:
if errors is IGNORE:
return value
elif errors is SET_NULL:
return None
else:
raise
def parsedatetime(
value: str,
dayfirst: bool = False,
yearfirst: bool = False,
errors: Optional[object] = None,
) -> Optional[str]:
"""
Parse a datetime and convert it to ISO datetime format: yyyy-mm-ddTHH:MM:SS
\b
- dayfirst=True: treat xx as the day in xx/yy/zz
- yearfirst=True: treat xx as the year in xx/yy/zz
- errors=r.IGNORE to ignore values that cannot be parsed
- errors=r.SET_NULL to set values that cannot be parsed to null
"""
if not value:
return value
try:
return parser.parse(value, dayfirst=dayfirst, yearfirst=yearfirst).isoformat()
except parser.ParserError:
if errors is IGNORE:
return value
elif errors is SET_NULL:
return None
else:
raise
def jsonsplit(
value: str, delimiter: str = ",", type: Callable[[str], object] = str
) -> str:
"""
Convert a string like a,b,c into a JSON array ["a", "b", "c"]
"""
return json.dumps([type(s.strip()) for s in value.split(delimiter)])