如何仅在python中比较基于月和年的两个日期

时间:2018-01-26 07:10:49

标签: python

我需要仅根据月份和年份比较两个日期,而不考虑日期或时间。我试过跟随,但没有给出正确的结果:

if lastMonthAllowed.month > lastUserUploadMonth.month and lastMonthAllowed.year > lastUserUploadMonth.year:
    #do something

有没有简单的方法来实现这个目标?

2 个答案:

答案 0 :(得分:2)

你可以这样做:

import datetime

def trunc_datetime(someDate):
return someDate.replace(day=1, hour=0, minute=0, second=0, microsecond=0)

a = trunc_datetime(datetime.datetime(2018,1,15))
b = trunc_datetime(datetime.datetime(2018,1,20))

print(a == b)
>>>True

答案 1 :(得分:1)

您可以使用datetime.datetime,其中包含yearmonth属性。 Check this link