Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two dates based on Month and Year only in python

Tags:

python

I need to compare two dates based on month and year only, without considering the day or time. I tried following but it does not give correct result:

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

Is there any simple way to achieve this?

like image 371
Tahreem Iqbal Avatar asked Dec 23 '22 10:12

Tahreem Iqbal


1 Answers

You could do it like this:

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
like image 80
tk78 Avatar answered Dec 25 '22 23:12

tk78