Slartibartfast
Slartibartfast

Reputation: 1190

Converting int to str in python is producing TypeError

I have the following code:

a = date.datetime.today().month
b = date.datetime.strptime(str(a) , '%m')

This code goes into error because it is expecting a string. variable a is int. How can i convert into to string. I tried str(a) and that did not work.

The error i get is :

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-24-80ff451251fc> in <module>
      1 a = date.datetime.today().month
----> 2 b = date.datetime.strptime(str(a) , '%m')

TypeError: 'str' object is not callable

Upvotes: 0

Views: 60

Answers (2)

S_Anuj
S_Anuj

Reputation: 373

try to do it like this:

import datetime
date = datetime.date.today()
a = date.today().month
from datetime import datetime
date_object = datetime.strptime(a, "%M")

datetime.datetime(1900, 1, 1, 0, 5)

date_object = datetime.strptime(a, "%m")

datetime.datetime(1900, 5, 1, 0, 0)

Upvotes: 2

gahooa
gahooa

Reputation: 137262

Your example works, except, that you have the date and datetime mixed up.

The import is datetime. Within, you have two classes:

  1. date for date related stuff
  2. datetime for datetime related stuff

Here is a working example

>>> import datetime
>>> a = datetime.date.today().month
>>> datetime.datetime.strptime(str(a) , '%m')
datetime.datetime(1900, 5, 1, 0, 0)

Upvotes: 1

Related Questions