Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a datetime.date object without the day be created in python?

Tags:

python

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?

like image 489
user2535775 Avatar asked Jun 30 '13 04:06

user2535775


1 Answers

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.

like image 149
Burhan Khalid Avatar answered Oct 18 '22 15:10

Burhan Khalid