user2535775
user2535775

Reputation: 111

Can a datetime.date object without the day be created in 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?

Upvotes: 11

Views: 10946

Answers (2)

lowtech
lowtech

Reputation: 2582

Pandas has Period class where you don't have to supply day if you don't 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

Upvotes: 9

Burhan Khalid
Burhan Khalid

Reputation: 174614

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.

Upvotes: 9

Related Questions