Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Convention for date with no year

Tags:

python

date

I have a script that looks at a list of birthdays and then calculates the age. Some birthdays have year, month, day and some only have month, day.

For the ones with years, I have dob = date(year, month, day)

But for the ones without years, what is the appropriate convention for storing the date, since date() requires a year argument?

Right now I'm saying that everyone without a birth year was born in the year 1500 (so I can at least identify them easily later on), but it's obviously a stupid solution.

like image 901
AutomaticStatic Avatar asked Oct 19 '22 21:10

AutomaticStatic


2 Answers

If there is no year; don't use datetime.date class. date must have year. Either compute date field on the fly everytime you need it if year is present, and/or make self.date property on your custom object to raise an error if it is used for an object without a year.

like image 94
jfs Avatar answered Oct 22 '22 13:10

jfs


I think it pays off to go a small extra mile when defining data structures (not with other things!) and not use a convention like your year 1500. Thus:

from dataclasses import dataclass

@dataclass
class Birthday:
    day: int
    month: int
    year: Optional[int] = None

    def is_valid(self) -> bool:
        try:
            dt = date(self.year, self.month, self.day)
            return True
        except ValueError:
            return False

The dataclass is for extra convenience only when creating or printing a birthday. Now you can:

birthday_without_year = Birthday(day=3, month=5)
birthday_with_year = Birthday(day=3, month=5, year=2000)

If you want, you can overwrite the default __init__ and check if the birthday is_valid if someone passes a year.

like image 24
tyrex Avatar answered Oct 22 '22 13:10

tyrex