Skip to content

Commit

Permalink
parse whole date with regex
Browse files Browse the repository at this point in the history
  • Loading branch information
cleder committed Oct 30, 2023
1 parent fc4a3e1 commit 1623c74
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 18 deletions.
8 changes: 4 additions & 4 deletions fastkml/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,11 +130,11 @@ def from_element(self, element: Element) -> None:
self.name = element.get("name")
simple_fields = element.findall(f"{self.ns}SimpleField")
for simple_field in simple_fields:
sfname = simple_field.get("name")
sftype = simple_field.get("type")
sf_name = simple_field.get("name")
sf_type = simple_field.get("type")
display_name = simple_field.find(f"{self.ns}displayName")
sfdisplay_name = display_name.text if display_name is not None else None
self.append(SimpleField(sfname, DataType(sftype), sfdisplay_name))
sf_display_name = display_name.text if display_name is not None else None
self.append(SimpleField(sf_name, DataType(sf_type), sf_display_name))

def etree_element(
self,
Expand Down
27 changes: 13 additions & 14 deletions fastkml/times.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@
# regular expression to parse a gYearMonth string
# year and month may be separated by a dash or not
# year is always 4 digits, month is always 2 digits
year_month = re.compile(r"^(?P<year>\d{4})(?:-?)(?P<month>\d{2})$")
year_month_day = re.compile(
r"^(?P<year>\d{4})(?:-)?(?P<month>\d{2})?(?:-)?(?P<day>\d{2})?$"
)


class KmlDateTime:
Expand Down Expand Up @@ -120,20 +122,17 @@ def parse(cls, datestr: str) -> Optional["KmlDateTime"]:
"""Parse a KML DateTime string into a KmlDateTime object."""
resolution = None
dt = None
if len(datestr) == 4:
year = int(datestr)
dt = arrow.get(year, 1, 1).datetime
resolution = DateTimeResolution.year
elif len(datestr) in {6, 7}:
ym = year_month.match(datestr)
if ym:
year = int(ym.group("year"))
month = int(ym.group("month"))
dt = arrow.get(year, month, 1).datetime
resolution = DateTimeResolution.year_month
elif len(datestr) in {8, 10}: # 8 is YYYYMMDD, 10 is YYYY-MM-DD
dt = arrow.get(datestr).datetime
year_month_day_match = year_month_day.match(datestr)
if year_month_day_match:
year = int(year_month_day_match.group("year"))
month = int(year_month_day_match.group("month") or 1)
day = int(year_month_day_match.group("day") or 1)
dt = arrow.get(year, month, day).datetime
resolution = DateTimeResolution.date
if year_month_day_match.group("day") is None:
resolution = DateTimeResolution.year_month
if year_month_day_match.group("month") is None:
resolution = DateTimeResolution.year
elif len(datestr) > 10:
dt = arrow.get(datestr).datetime
resolution = DateTimeResolution.datetime
Expand Down

0 comments on commit 1623c74

Please sign in to comment.