Python 3.6-在将某些字符串转换为时间时出现错误“需要整数(类型为str)” [英] Python 3.6 - getting error 'an integer is required (got type str)' while converting some strings to time

查看:814
本文介绍了Python 3.6-在将某些字符串转换为时间时出现错误“需要整数(类型为str)”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个函数,该函数接受其中一列中包含一些原始数字数据的行,并将其转换为适当的分钟数(csv文件)。如果我需要与它们纠缠,那么所有列都保留为字符串,因为字符串使它更容易。但是,将某些数据转换为时间格式(再次以字符串形式)时,出现标题中描述的错误。我的函数如下所示:

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

datetime.datetime.fromtimestamp(i).strftime(form,'minutes') 是运行 duration_in_mins()时根据追溯得到的错误。追溯是否告诉我先将字符串转换为数字然后转换为时间?日期时间不能直接将字符串转换为时间吗?

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

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

请注意, strptime 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

您可能会看到错误来自 fromtimestamp(ts) ,它需要一个整数时间戳记参数而不是一个str。

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

在某个时候将这个参数转换为int并一切都应该没事。

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

这篇关于Python 3.6-在将某些字符串转换为时间时出现错误“需要整数(类型为str)”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆