Skip to content Skip to sidebar Skip to footer

Python 3.6 - Getting Error 'an Integer Is Required (got Type Str)' While Converting Some Strings To Time

I wrote a function that takes in a row that has some raw numeric data in one of the columns and converts it to appropriate minutes (its a csv file). All the columns have been kept

Solution 1:

As you say, datetime.fromtimestamp() requires a number but you are giving it a string. Python has a philosophy "In the face of ambiguity, refuse the temptation to guess" so it will throw an exception if you give a function an object of the wrong type.

Other problems with the code:

  • The strftime() method will only take one argument but you're passing it a second one.

  • Also, did you mean to nest those loops? Every time you append another value to duration you convert all of the values in the list to times, and then if the conversion did work you are just throwing away the result of the conversion and not saving it anywhere.

Solution 2:

First, there is an incoherence between your code and the reported error:

datetime.datetime.fromtimestamp(i).strftime(form, 'minutes') # Conversion

and

line 39, in duration_in_mins
datetime.datetime.fromtimestamp(i).strptime(form, 'minutes')
TypeError: an integer is required (got typestr)

Please note strptime is different than strftime

Then, you should split the line with error to understand what function exactly caused the exception:

x = datetime.datetime.fromtimestamp(i)
x.strftime(form, 'minutes') # Conversion

And you will probably see that the error comes from fromtimestamp(ts) which needs an integer timestamp argument instead of a str.

Convert this argument as int at some point and everything should be ok.

Post a Comment for "Python 3.6 - Getting Error 'an Integer Is Required (got Type Str)' While Converting Some Strings To Time"