Is there a direct way to ignore parts of a python datetime object?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping
--
Chapters
00:00 Question
00:52 Accepted answer (Score 6)
01:04 Answer 2 (Score 9)
01:24 Answer 3 (Score 4)
01:53 Answer 4 (Score 2)
02:16 Thank you
--
Full question
https://stackoverflow.com/questions/3915...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #datetime
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping
--
Chapters
00:00 Question
00:52 Accepted answer (Score 6)
01:04 Answer 2 (Score 9)
01:24 Answer 3 (Score 4)
01:53 Answer 4 (Score 2)
02:16 Thank you
--
Full question
https://stackoverflow.com/questions/3915...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #datetime
#avk47
ANSWER 1
Score 9
(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]
ACCEPTED ANSWER
Score 6
Try:
a.replace(year=1,microsecond=0) == b.replace(year=1,microsecond=0)
ANSWER 3
Score 4
You can also consider comparing formatted date strings consisting of the fields you wish to include in the comparison. This allows you to be somewhat explicit while using shortened versions of the fields (as opposed to accessing a.year, a.month, etc.).
from datetime import datetime
date_string = '%m %d %H %M %S'
a = datetime(2015, 7, 4, 1, 1, 1)
b = datetime(2016, 7, 4, 1, 1, 1)
print(a.strftime(date_string) == b.strftime(date_string)) # True
ANSWER 4
Score 2
def cmp(a,b):
return (a > b) - (a < b)
d1=(2015,7,4,1,1,1)
d2=(2016,7,4,1,1,1)
cmp(list(d1)[1:],list(d2)[1:])
Returns 0 - they are the same, i.e. 0 differences
d1=(2015,7,4,1,1,1)
d2=(2015,2,4,1,1,1)
cmp(list(d1)[1:], list(d2)[1:])
returns -1, there is a difference.