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

I try to enter a date in python, but sometimes I donโ€™t know the exact day or month. Therefore, I would like to record only a year. I would like to do something like: datetime.date (year = 1940, month = "0 or None", day = "0 or None")
Is there any code for this? Or, if not, how do you manage to deal with this problem?

+6
source share
2 answers

Unfortunately, you cannot pass 0 because there is no month 0 , so you get ValueError: month must be in 1..12 , you cannot miss a month or day, because both of them are necessary.

If you do not know the exact year or month, just go to 1 month and day, and then save only part of the year.

 >>> 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 an abbreviation for the first.

However, if you just want to keep the year, you do not need a datetime object. You can save the integer value separately. A date object implies a month and a day.

+4
source

Pandas has a Period class in which you do not need to specify a day if you do not know that:

 import pandas as pd pp = pd.Period('2013-12', 'M') print pp print pp + 1 print pp - 1 print (pp + 1).year, (pp + 1).month 

Output:

 2013-12 2014-01 2013-11 2014 1 
+2
source

Source: https://habr.com/ru/post/948409/


All Articles