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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值