概述
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 as strings if at all I need to wrangle with them since strings makes it easier. However, when converting some data into time format (again in strings), I get the error described in the title. My functions looks like the following:
def duration_in_mins(row, city):
duration = [] # Make an empty list
form = '%M.%S'
if city == 'X':
city_file = open('X.csv')
city_csv = csv.reader(city_file)
for row in city_csv:
duration.append(row[1]) # The column that contains the strings
for i in duration:
datetime.datetime.fromtimestamp(i).strftime(form, 'minutes') # Conversion
else:
return 'Error'
return duration
The line datetime.datetime.fromtimestamp(i).strftime(form, 'minutes') is where I'm getting the error according to traceback when I run duration_in_mins(). Is the traceback telling me to convert the string into numeric first and then to time? Can datetime not convert strings directly into time?
duration_in_mins(5, 'X)
line 39, in duration_in_mins
datetime.datetime.fromtimestamp(i).strptime(form, 'minutes')
TypeError: an integer is required (got type str)
解决方案
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 type str)
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.
最后
以上就是虚幻黑米为你收集整理的python exception转字符串,Python 3.6-在将某些字符串转换为时间时出现错误“需要整数(类型为str)”...的全部内容,希望文章能够帮你解决python exception转字符串,Python 3.6-在将某些字符串转换为时间时出现错误“需要整数(类型为str)”...所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复