Uran Luis
Uran Luis

Reputation: 25

Can't convert string to date in python

I want to convert a string into a date. Here's the code:

cumple = input('When is your birthday? ')
formato = '%d/%m/%Y'
cumpleFecha = datetime.datetime.strptime(cumple, formato)
print('Your birthday is ' + cumpleFecha)

And the error I'm getting is:

TypeError: Can't convert 'datetime.datetime' object to str implicitly

Upvotes: 2

Views: 4902

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121962

That's because a datetime object is not a string, you cannot just concatenate (using +) to a string.

Remove the +, and pass in the datetime object as a separate argument:

print('Your birthday is', cumpleFecha)

This leaves conversion to a string to the print() function.

Or convert it to a string explicitly:

print('Your birthday is ' + str(cumpleFecha))

or

print('Your birthday is ' + cumpleFecha.strftime('%d %B %Y')

Upvotes: 3

Related Questions