python - datetime.datetime.strptime 将字符串转换为日期时间时出现错误 未转换日期 remands : 2

标签 python python-2.7 pandas datetime

csv文件有18列,其中6列分别是'年','月','日','小时','分钟','秒',其数据类型均为INT,除了列'秒'是 float 。

首先,我将int和float类型转换为字符串,然后将它们连接起来,然后使用datetime.datetime.strptime将它们转换为datetype。但不知怎的,它不起作用。

它返回:

File "/anaconda3/lib/python2.7/_strptime.py", line 335, in _strptime
data_string[found.end():])

ValueError: unconverted data remains: 2

使用的代码是: 将 pandas 导入为 pd 导入时间 导入日期时间

df=pd.read_csv('/Users/song/PycharmProjects/AAA/nppanda/LASTROW/LASTROW_GTE Aurich.csv')
df.dropna(how='any')
df.columns=['0','1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16','17']

df['18']=df['12'].apply(lambda x:str(x))
df['19']=df['13'].apply(lambda x:str(x))
df['20']=df['14'].apply(lambda x:str(x))
df['21']=df['15'].apply(lambda x:str(x))
df['22']=df['16'].apply(lambda x:str(x))
df['23']=df['17'].apply(lambda x:str(x))

df['24']=df['18'].str.cat(df['19'],sep='-')
df['24']=df['24'].str.cat(df['20'],sep='-')
df['24']=df['24'].str.cat(df['21'],sep=' ')
df['24']=df['24'].str.cat(df['22'],sep=':')
df['24']=df['24'].str.cat(df['23'],sep=':')

def has_seconds(a_string):
    if a_string.find('.')!=-1:
        transtime=datetime.datetime.strptime(a_string,'%Y-%m-%d %H:%M:%S.%f')
    elif a_string.find('.')==-1:
        transtime=datetime.datetime.strptime(a_string,'%Y-%m-%d %H:%M:%S')
    return transtime   

df['25']=df['24'].apply(has_seconds)

最佳答案

你对 Pandas 的想法想得太多了。如果您的列命名适当,您可以直接输入 pd.to_datetime 。此外,避免将 Python 的 datetime 模块与 Pandas 一起使用:

df = pd.DataFrame([[2015, 12, 20, 15, 10, 3.1234],
                   [2018, 5, 15, 10, 12, 65.432]],
                  columns=['year','month','day','hours','minutes','seconds'])

df['datetime'] = pd.to_datetime(df)

print(df)

   year  month  day  hours  minutes  seconds                   datetime
0  2015     12   20     15       10   3.1234 2015-12-20 15:10:03.123400
1  2018      5   15     10       12  65.4320 2018-05-15 10:13:05.432000

注意日期时间值在内部存储为整数。避免您当前正在尝试的往返是有意义的:

  1. str,csv 输入文件
  2. int 通过 pd.read_csv
  3. str 通过 pd.Series.apply
  4. int 通过 datetime.strptime

所有这些都非常昂贵且不必要。

关于python - datetime.datetime.strptime 将字符串转换为日期时间时出现错误 未转换日期 remands : 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53154628/

相关文章:

python - 如何在 django 中为 SQLServer 数据库创建身份验证系统?

python - numpy 数组映射并取平均值

python - 获取 'package' 和 'endpackage' 可选字符串之外的结构名称列表

python - 根据其他列的 if-else 填充 pandas DataFrame 的新列

python pandas 将多年的 yyyy-mm-dd 分配为累计周数

java - 无法使用 Java 进程执行参数包含 #(哈希)字符的 python 可执行文件

python - 测试发布请求时 Django 消息中间件问题

python - 为什么hasattr会执行@property装饰器代码块

python - 如何在python中删除字符串中字符的所有实例?

python - 上传文件到jupyter时忽略ds_store文件的建议