1616from .instant_ import Instant
1717from .period_ import Period
1818
19+ UNIT_MAPPING = {1 : "year" , 2 : "month" , 3 : "day" }
20+
1921
2022def build_instant (value : Any ) -> Optional [types .Instant ]:
2123 """Build a new instant, aka a triple of integers (year, month, day).
@@ -262,12 +264,10 @@ def parse_period(value: str) -> Optional[types.Period]:
262264 if not (value and isinstance (value , str )):
263265 raise AttributeError
264266
265- # If it's negative, next!
266- if value [0 ] == "-" :
267+ # If it's negative period , next!
268+ if value [0 ] == "-" or len ( value . split ( ":" )) != 1 :
267269 raise ValueError
268270
269- unit = _parse_unit (value )
270-
271271 try :
272272 date = pendulum .parse (value , exact = True )
273273
@@ -277,41 +277,6 @@ def parse_period(value: str) -> Optional[types.Period]:
277277 if not isinstance (date , Date ):
278278 raise ValueError
279279
280- instant = Instant ((date .year , date .month , date .day ))
281-
282- return Period ((unit , instant , 1 ))
283-
284-
285- def _parse_unit (value : str ) -> str :
286- """Determine the date unit of a date string.
287-
288- Args:
289- value (str): The date string to parse.
290-
291- Returns:
292- A date unit.
293-
294- Raises:
295- ValueError: when no date unit can be determined.
296-
297- Examples:
298- >>> _parse_unit("2022")
299- 'year'
300-
301- >>> _parse_unit("2022-03-01")
302- 'day'
303-
304- """
305-
306- length = len (value .split ("-" ))
307-
308- if length == 1 :
309- return YEAR
310-
311- elif length == 2 :
312- return MONTH
313-
314- elif length == 3 :
315- return DAY
316-
317- raise ValueError
280+ unit = UNIT_MAPPING [len (value .split ("-" ))]
281+ start = Instant ((date .year , date .month , date .day ))
282+ return Period ((unit , start , 1 ))
0 commit comments