Skip to content

Commit

Permalink
Parse ISO8601 with regexp (#2)
Browse files Browse the repository at this point in the history
  • Loading branch information
raymondjavaxx authored Dec 6, 2023
1 parent e3e5b8b commit af6f1cc
Showing 1 changed file with 6 additions and 9 deletions.
15 changes: 6 additions & 9 deletions mp_yearmonth/yearmonth.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@
# This module is part of mp-yearmonth and is released under
# the MIT License: https://opensource.org/license/mit/

import re
import calendar
import datetime
from typing import Iterator, Tuple

_FORMAT_PATTERN = re.compile(r"^(\d{4})-(\d{2})$")


class YearMonth:
"""A class representing a year and month.
Expand Down Expand Up @@ -127,17 +130,11 @@ def current(cls) -> "YearMonth":
@classmethod
def parse(cls, s: str) -> "YearMonth":
"""Parses a string in the format YYYY-MM into a YearMonth object."""
is_valid = (
isinstance(s, str)
and len(s) == 7
and s[4] == "-"
and s[:4].isdigit()
and s[5:].isdigit()
)
if not is_valid:
match = _FORMAT_PATTERN.match(s)
if not match:
raise ValueError(f"Invalid YearMonth string format: {s}")

year, month = s[:4], s[5:]
year, month = match.groups()
return cls(int(year), int(month))

def next(self) -> "YearMonth":
Expand Down

0 comments on commit af6f1cc

Please sign in to comment.