Skip to content

Commit

Permalink
parse gYearMonth with regex
Browse files Browse the repository at this point in the history
  • Loading branch information
cleder committed Jan 13, 2023
1 parent dba7c43 commit 18550d3
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 26 deletions.
2 changes: 1 addition & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -109,4 +109,4 @@ Geometry collection (MultiGeometry). You cannot assign different values of
Currently, the only major feature missing for the full Google Earth experience
is the `gx extension
<https://developers.google.com/kml/documentation/kmlreference#kmlextensions>`_.
Please submit a PR with the features you'd like to see implementd.
Please submit a PR with the features you'd like to see implemented.
44 changes: 19 additions & 25 deletions fastkml/times.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Date and time handling in KML."""
import re
from datetime import date
from datetime import datetime
from typing import Optional
Expand All @@ -15,6 +16,12 @@
from fastkml.base import _BaseObject
from fastkml.types import Element

# 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
# capture groups are named year and month, the dash is not captured
year_month = re.compile(r"^(?P<year>\d{4})(?:-?)(?P<month>\d{2})$")


class _TimePrimitive(_BaseObject):
"""The dateTime is defined according to XML Schema time.
Expand Down Expand Up @@ -53,33 +60,20 @@ def get_resolution(
return resolution

def parse_str(self, datestr: str) -> Tuple[datetime, str]:
resolution = "dateTime"
year = 0
month = 1
day = 1
if len(datestr) == 4:
resolution = "gYear"
year = int(datestr)
dt = datetime(year, month, day)
elif len(datestr) == 6:
resolution = "gYearMonth"
year = int(datestr[:4])
month = int(datestr[-2:])
dt = datetime(year, month, day)
elif len(datestr) == 7:
resolution = "gYearMonth"
year = int(datestr.split("-")[0])
month = int(datestr.split("-")[1])
dt = datetime(year, month, day)
elif len(datestr) in [8, 10]:
resolution = "date"
dt = dateutil.parser.parse(datestr)
elif len(datestr) > 10:
resolution = "dateTime"
dt = dateutil.parser.parse(datestr)
else:
raise ValueError
return dt, resolution
return datetime(year, 1, 1), "gYear"
if len(datestr) in {6, 7}:
ym = year_month.match(datestr)
if ym:
year = int(ym.group("year"))
month = int(ym.group("month"))
return datetime(year, month, 1), "gYearMonth"
if len(datestr) in {8, 10}: # 8 is YYYYMMDDS
return dateutil.parser.parse(datestr), "date"
if len(datestr) > 10:
return dateutil.parser.parse(datestr), "dateTime"
raise ValueError

def date_to_string(
self,
Expand Down

0 comments on commit 18550d3

Please sign in to comment.