Santosh Sahu Santosh Sahu - 7 months ago 32
Python Question

Error while comparing string after transforming from datetime

I am converting datetime to string and then comparing it with string from from a file. But the "==" comparision fails.

Below is my code:

date_input =
dat = date_input.strftime("%Y-%m-%d %H:%M:%S.%f")

command = 'echo %s > /media/mmcblk0p1/testCard.txt' %dat
stdin, stdout, stderr = self._sshclient.exec_command(command,timeout=10)
command = 'cat /media/mmcblk0p1/testCard.txt'
stdin, stdout, stderr = self._sshclient.exec_command(command, timeout=10)
date_output ='UTF-8')
self.logger.debug("dat=%s date_output=%s ",dat,date_output)

if(date_output == dat): #FAILS
self.logger.debug("read from file successful")
self.logger.debug("read from file unsucessful")
self.logger.exception('%s %s error, readtimeout',
ip, self.__class__.__name__)
self.add_response("read error/timeout")
except :
self.logger.exception('%s %s error, writetimeout',
ip, self.__class__.__name__)
self.add_response("write error/timeout")


dat=2016-09-06 15:49:49.104030 date_output=2016-09-06 15:49:49.104030
read from file unsucessful
dat=2016-09-06 15:49:49.237551 date_output=2016-09-06 15:49:49.237551
read from file unsucessful

I am unable to figure out the comparision failure, it prints "read from file unsuccessful" Is it for the or datetime.

NOTE: There is no exception in this code, and the values are same if i use print method also.

Any solution is welcome


Have you tried using .strip()

if(date_output.strip() == dat.strip()):   

If there are any whitespace characters on either end of the string (which i think there are) then .strip() takes them out and we can compare the strings without the whitespace characters.