Python 仅包含年和月的日期对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14425133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Date object with year and month only
提问by daGrevis
Is it possible to create dateobject with year and month only? I don't need day.
是否可以仅使用年和月创建日期对象?我不需要一天。
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
I'm using the date object as key in my dictionary and January 20 must have the same key as January 21, because they are in same month and year.
我在字典中使用日期对象作为键,1 月 20 日必须与 1 月 21 日具有相同的键,因为它们在同一月份和年份。
I used a simple integer before that as a month number. Unfortunately I need to know the year too!
在此之前我使用了一个简单的整数作为月份数。不幸的是,我也需要知道年份!
采纳答案by Martijn Pieters
No, you can't do that. For your usecase, use a tuple instead:
不,你不能那样做。对于您的用例,请改用元组:
key = (2013, 1)
Since you don't need to do date manipulations on the value a tuple more than suffices.
由于您不需要对值进行日期操作,因此一个元组就足够了。
回答by reader_1000
As an addition to other answer, you can use namedtuple.
作为其他答案的补充,您可以使用namedtuple。
from collections import namedtuple
MyDate = namedtuple('MyDate', ['month', 'year'])
dkey = MyDate(year=2013, month=1)
回答by Haimei
If you want to use datetime, you must follow its attributes. Here I quote it from the official website:
如果要使用datetime,则必须遵循其属性。这里我引用官网的:
"An idealized naive date, assuming the current Gregorian calendar always was, and always will be, in effect. Attributes: year, month, and day."
“一个理想化的天真日期,假设当前的公历一直是,也将是,实际上。属性:年、月和日。”
So, you can't ignore day and remember to give assignment.
所以,你不能忽视一天,记得分配任务。
回答by zeroclyy
import datetime
date = datetime.date(year=2013, month=1, day=4)
str(date.year) + '-' + str(date.month)

