I'm trying to enter a date in Python but sometimes I don't know the exact day or month. So I would like to record only the year. I would like to do something like:
datetime.date(year=1940, month="0 or None", day="0 or None")
Is there a code for doing this? Or if not, how would you manage to deal with this problem?
Unfortunately, you can't pass 0
because there is no month 0
so you'll get ValueError: month must be in 1..12
, you cannot skip the month or the day as both are required.
If you do not know the exact year or month, just pass in 1 for the month and day and then keep only the year part.
>>> d = datetime.date(year=1940, month=1, day=1)
>>> d
datetime.date(1940, 1, 1)
>>> d.year
1940
>>> d = datetime.date(year=1940, month=1, day=1).year
>>> d
1940
The second statement is a shorthand for the first.
However, if you want to just store the year, you don't need a datetime object. You can store the integer value separately. A date object implies month and day.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With