irongit

A parser inspired by the django orm.

gparser/parsers/translators.py
37 lines1.1 KBPython
1"""
2Translator functions for the basics.
3"""
4import re
5import datetime as dt
6
7
8def split_hour_minute(str):
9 """Extracts hours and minutes into separate strings"""
10 if ':' in str and len(str) < 5 or len(str) < 4:
11 raise ValueError(
12 f'Hours and minutes must have at least 4 characters without : and 5 with :.')
13 str = ''.join(re.findall(r'\d+', str))
14 return str[:-2], str[-2:]
15
16
17def hour_minute_to_delta(cls, str):
18 """Converts hour and minute string into a time delta"""
19 hours, minutes = split_hour_minute(str)
20 return dt.timedelta(hours=int(hours), minutes=int(minutes))
21
22
23def hour_minute_to_int(cls, str):
24 """Converts hours and minutes to a total number of minutes"""
25 hours, minutes = split_hour_minute(str)
26 return int(minutes)+int(hours)*60
27
28
29def phone(cls, str):
30 """Converts numbers to a phone number with country code readiness"""
31 nums = ''.join(re.findall(r'\d+', str))
32 if len(nums) < 4:
33 raise TypeError(f'Impossible phone number {str}.')
34 if nums[:3] == '011':
35 return '+'+nums[3:]
36 else:
37 return '+1'+nums