简体   繁体   中英

Why does comparing these 2 dates fail in python when printed they are the same

I'm trying to compare 2 dates in python, when I print the dates they are the same but the comparison fails.

import datetime
today = datetime.date.today()
print today
print '2019-04-30'
d1 = today
d2 = '2019-04-30'
if d1 == d2:
    print 'match'
else:
    print 'nomatch'

Totally confused why dates that look the same but the comparison fails.

They're not the same. You can test it out by checking their types

type(d1)
<class 'datetime.date'>

type(d2)
<class 'str'>

Printing d1 gives you the same string because datetime objects have a __repr__ method that returns string.

因为其中一个是字符串,另一个是日期格式,并且日期格式和字符串不能与value相同。

The problem here is that you are comparing a datetime object and a string. For a valid comparisson you should parse d2 using datetime.datetime.strptime and then compare:

import datetime
d2 = '2019-04-30'
d2_datetime = datetime.datetime.strptime(d2, '%Y-%m-%d')

Now if you check for equality you will see that both instances are the same:

datetime.date.today() == d2_datetime.date()
# True

Because python is a strongly-typed language. You're comparing string (d2) with a date object (d1). That's why they are not equal.

You can covert d1 to date d1 = datetime.date(2019, 4, 30) . That way d2 and d1 will be equal.

you should do:

today = str(datetime.date.today())

Both d1 and d2 are variables of different types, hence the comparison fails as below

import datetime
today = datetime.date.today()
print today
print '2019-04-30'
d1 = today
d2 = '2019-04-30'

#Both types are different, as seen below
print type(d1)
#<type 'datetime.date'>
print type(d2)
#<type 'str'>

if d1 == d2:
    print 'match'
else:
    print 'nomatch'

To compare them, make sure both are of same types, and then the values will be compared, for example the below returns True since both datetime string evaluate to the same datetime object

import datetime

d1 = datetime.datetime.strptime('2019-04-30', '%Y-%m-%d')
d2 = datetime.datetime.strptime('04-30-2019', '%m-%d-%Y')

print(d1 == d2)
#True

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM