可以在python中创建没有日期的datetime.date对象吗?

use*_*775 8 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")
Run Code Online (Sandbox Code Playgroud)

Is there a code for doing this? Or if not, how would you manage to deal with this problem?

Bur*_*lid 5

不幸的是,0由于没有月份,0所以您无法通过,因此您将获得ValueError: month must be in 1..12,不能跳过月份或日期,因为两者都需要。

如果您不知道确切的年份或月份,只需在月份和日期中输入1,然后仅保留年份部分即可。

>>> 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
Run Code Online (Sandbox Code Playgroud)

第二句话是第一句话的简写。

但是,如果只想存储年份,则不需要日期时间对象。您可以单独存储整数值。日期对象表示月份和日期。


low*_*ech 5

Pandas 有 Period 类,如果您不知道,则不必提供日期:

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
Run Code Online (Sandbox Code Playgroud)

输出:

2013-12
2014-01
2013-11
2014 1
Run Code Online (Sandbox Code Playgroud)