我是靠谱客的博主 虚幻黑米,这篇文章主要介绍python exception转字符串,Python 3.6-在将某些字符串转换为时间时出现错误“需要整数(类型为str)”...,现在分享给大家,希望可以做个参考。

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内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(46)

评论列表共有 0 条评论

立即
投稿
返回
顶部