TypeError: can only concatenate str (not "datetime.datetime") to str in Python

Dung Do Tien Sep 13 2021 178

 Hello you guys, I am a newbie in Python and I'm also studying more about Python.

I have a small assignment, I have a small function and I want to display the current time after sleep. Like this:

import datetime
import time

x = datetime.datetime.now()
print (x)
time.sleep(5)
y = datetime.datetime.now()
print (y)
print ("Then: " + x +"\n Now: " + y)

But I get an exception TypeError: can only concatenate str (not "datetime.datetime") to str when I run code above.

2021-09-13 16:41:15.204024
2021-09-13 16:41:20.209113
Traceback (most recent call last):
  File "main.py", line 9, in <module>
    print ("Then: " + x +"\n Now: " + y)
TypeError: can only concatenate str (not "datetime.datetime") to str

And I am using python 3.8.2

Anyone can explain it to me? How can I solve it?

Thanks for any response.

Have 1 answer(s) found.
  • M

    Marry Christ Sep 13 2021

    You can change the line of code:

    x = datetime.datetime.now()

    to 

    x = datetime.now()
    x = str(x)

    Change same code for y variable and don't forget to change the import datetime package to from datetime import datetime

    Full fix example:

    from datetime import datetime
    import time
    
    #x = datetime.datetime.now()
    x = datetime.now()
    x = str(x)
    print (x)
    
    time.sleep(5)
    y = datetime.now()
    y = str(y)
    
    print (y)
    print ("Then: " + x +"\n Now: " + y)

    #Output

    2021-09-13 16:52:08.338673
    2021-09-13 16:52:13.341120
    Then: 2021-09-13 16:52:08.338673
     Now: 2021-09-13 16:52:13.341120

     

Leave An Answer
* NOTE: You need Login before leave an answer

* Type maximum 2000 characters.

* All comments have to wait approved before display.

* Please polite comment and respect questions and answers of others.

Popular Tips

X Close