29

是否可以仅使用年和月创建日期对象?我不需要白天。

In [5]: from datetime import date

In [6]: date(year=2013, month=1)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-a84d4034b10c> in <module>()
----> 1 date(year=2013, month=1)

TypeError: Required argument 'day' (pos 3) not found

我在字典中使用日期对象作为键,并且 1 月 20 日必须与 1 月 21 日具有相同的键,因为它们位于同一月份和年份。

在此之前我使用了一个简单的整数作为月份数。不幸的是,我也需要知道年份!

4

5 回答 5

21

不,你不能那样做。对于您的用例,请改用元组:

key = (2013, 1)

由于您不需要对值进行日期操作,因此一个元组就足够了。

于 2013-01-20T13:50:57.113 回答
16

作为其他答案的补充,您可以使用 namedtuple。

from collections import namedtuple
MyDate = namedtuple('MyDate', ['month', 'year'])
dkey = MyDate(year=2013, month=1)
于 2013-01-20T13:56:34.030 回答
6
import datetime

date = datetime.date(year=2013, month=1, day=4)
str(date.year) + '-' + str(date.month)
于 2016-08-26T04:10:02.993 回答
3

如果你想使用datetime,你必须遵循它的属性。这里我引用官网的一段话:

“一个理想化的天真日期,假设当前的公历一直有效,并且永远都会有效。属性:年、月和日。”

所以,你不能忽略一天,记得给任务。

于 2014-01-31T01:58:40.103 回答
0

这实现了一个类似于 datetime.date 的类,但您无需指定日期。即它允许您“创建仅包含年和月的日期对象”。

class Mdate(datetime.date):
    """ A datetime.date where day doesn't matter. """

    def __new__(cls, year, month):
        """Python calls __new__ instead of __init__ for immutable objects."""
        return super().__new__(cls, year, month, 1)

    def __repr__(self):
        """Because you're implementing __new__ you also need __repr__ or else you get
        TypeError: __new__() takes 3 positional arguments but 4 were given."""
        return '{0}({1}, {2}, 1)'.format(self.__class__.__name__, self.year, self.month)

    def __reduce__(self):
        """You need __reduce__ to support pickling."""
        return (self.__class__, (self.year, self.month))

我有一大堆代码,其中月份的日期无关紧要,从日期构造函数中删除日期可以澄清该代码。

样品用途:

d = Mdate(2020, 12)
于 2020-07-11T16:29:49.590 回答