X-Git-Url: https://plomlompom.com/repos/foo.html?a=blobdiff_plain;f=plomtask%2Fdays.py;h=02ad1a8f5223e1dbaee1ef445fd4e9b211ad4842;hb=9c3ba57169fdc71d3ffefd4c7c20cae4e89f9c9c;hp=071b0b1b27d76b676d02ee4d4530563a5ba547b5;hpb=b557c789f4eec704db0e6276390395fac5d8db9e;p=plomtask diff --git a/plomtask/days.py b/plomtask/days.py index 071b0b1..02ad1a8 100644 --- a/plomtask/days.py +++ b/plomtask/days.py @@ -1,15 +1,47 @@ """Collecting Day and date-related items.""" from datetime import datetime +from sqlite3 import Row +from plomtask.misc import HandledException +from plomtask.db import DatabaseConnection DATE_FORMAT = '%Y-%m-%d' +def date_valid(date: str): + """Validate date against DATE_FORMAT, return Datetime or None.""" + try: + result = datetime.strptime(date, DATE_FORMAT) + except (ValueError, TypeError): + return None + return result + + class Day: """Individual days defined by their dates.""" def __init__(self, date: str): self.date = date - self.datetime = datetime.strptime(date, DATE_FORMAT) + self.datetime = date_valid(self.date) + if not self.datetime: + raise HandledException(f'Given date of wrong format: {self.date}') + + @classmethod + def add(cls, db_conn: DatabaseConnection, date: str): + """Add (or re-write) new Day(date) to database.""" + db_conn.exec('REPLACE INTO days VALUES (?)', (date,)) + + @classmethod + def from_table_row(cls, row: Row): + """Make new Day from database row.""" + return cls(row[0]) + + @classmethod + def all(cls, db_conn: DatabaseConnection): + """Return list of all Days in database.""" + days = [] + for row in db_conn.exec('SELECT * FROM days'): + days += [cls.from_table_row(row)] + return days @property def weekday(self):