确定较大的月份,忽略日期

1 python datetime date python-datetime

我可以在 python 中编写什么函数来确定 的日期是否f大于t,忽略日期部分 - 它显然是?

t = datetime.date(2014, 12, 30)
f = datetime.date(2015, 1 ,2)
Run Code Online (Sandbox Code Playgroud)

我尝试了以下方法:

if t.month > f.month:
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用,因为它没有考虑年份。我只想使用年份和月份,而不是日期。

请注意,“t”也可能是datetime.datetime(2015, 2, 2)

Mar*_*ers 5

您可以将日期与day设置为的组件进行比较1

t.replace(day=1) < f.replace(day=1)
Run Code Online (Sandbox Code Playgroud)

或比较年份和月份:

if t.year < f.year or (t.year == f.year and t.month < f.month):
Run Code Online (Sandbox Code Playgroud)

后者通过元组比较更容易测试:

if (t.year, t.month) < (f.year, f.month):
Run Code Online (Sandbox Code Playgroud)

演示:

>>> from datetime import date
>>> t = date(2015, 1, 2)
>>> f = date(2015, 2, 2)
>>> t.replace(day=1) < f.replace(day=1)
True
>>> t.year < f.year or (t.year == f.year and t.month < f.month)
True
>>> (t.year, t.month) < (f.year, f.month)
True
>>> t = date(2014, 12, 30)
>>> f = date(2015, 1, 2)
>>> t.replace(day=1) < f.replace(day=1)
True
>>> t.year < f.year or (t.year == f.year and t.month < f.month)
True
>>> (t.year, t.month) < (f.year, f.month)
True
Run Code Online (Sandbox Code Playgroud)