Concatenate byte with string in Python 3.5.2

3

I am making an application where I detect data from a sensor from Arduino and I want to print them together with the date and time. The data I read from the Arduino serial port is byte type, while the date and time are str.

I want to concatenate these data to print them with this line of code:

temperatura = ser.readline()

time_hhmmss = time.strftime('%H:%M:%S')
date_mmddyyyy = time.strftime('%d/%m/%Y')

print(temperatura + ',' + time_hhmmss + ',' + date_mmddyyyy)

But this error throws me: TypeError: can not concate bytes to str

I've looked for a way to concatenate them but I can not achieve it. I indicate that the data if I capture it from Arduino. I await your help. Thanks.

    
asked by Juan Sánchez 28.09.2016 в 08:30
source

2 answers

3

It's as simple as converting from bytes to str (by default, coded in utf-8 ):

print(temperatura.decode() + ',' + time_hhmmss + ',' + date_mmddyyyy)

Although it can be improved a little more:

from datetime import datetime

temperatura = ser.readline()

print("{} ºC, {:%H:%M:%S, %d/%m/%Y}".format(temperatura.decode(), datetime.now())
    
answered by 28.09.2016 / 10:40
source
2

Try this way of concatenating, it should work in both Python 3 and Python 2:

print(",".join((temperatura,time_hhmmss,date_mmddyyyy)))
    
answered by 28.09.2016 в 08:46