Santosh Sahu Santosh Sahu - 3 months ago 8
Python Question

Error while comparing string after transforming from datetime

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

Below is my code:

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

command = 'echo %s > /media/mmcblk0p1/testCard.txt' %dat
try:
stdin, stdout, stderr = self._sshclient.exec_command(command,timeout=10)
command = 'cat /media/mmcblk0p1/testCard.txt'
try:
stdin, stdout, stderr = self._sshclient.exec_command(command, timeout=10)
date_output = stdout.read().decode(encoding='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")
else:
self.logger.debug("read from file unsucessful")
except:
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")


Output



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 stdout.read() 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

Answer

Have you tried using .strip()

http://www.tutorialspoint.com/python/string_strip.htm

Example:
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.