Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a direct way to ignore parts of a python datetime object?

I'm trying to compare two datetime objects, but ignoring the year. For example, given

a = datetime.datetime(2015,07,04,01,01,01)
b = datetime.datetime(2016,07,04,01,01,01)

I want a == b to return True by ignoring the year. To do a comparison like this, I imagine I could just create new datetime objects with the same year like:

c = datetime.datetime(2014,a.month,a.day,a.hour,a.minute,a.second)
d = datetime.datetime(2014,b.month,b.day,b.hour,b.minute,b.second)

However, this doesn't seem very pythonic. Is there a more direct method to do a comparison like what I'm asking?

I'm using python 3.4.

like image 297
jsamsf Avatar asked Nov 29 '22 22:11

jsamsf


1 Answers

(a.month, a.day, a.hour, a.minute, a.second == 
 b.month, b.day, b.hour, b.minute, b.second)

A less explicit method is to compare the corresponding elements in the time tuples:

a.timetuple()[1:6] == b.timetuple()[1:6]
like image 107
Alexander Avatar answered Dec 05 '22 03:12

Alexander