The Python Oracle

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

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------

Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT


Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop

--

Chapters
00:00 Is There A Direct Way To Ignore Parts Of A Python Datetime Object?
00:37 Answer 1 Score 9
00:52 Answer 2 Score 2
01:09 Answer 3 Score 4
01:31 Accepted Answer Score 6
01:38 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.