ValueError:时间数据与格式不匹配'%Y-%m-%d%H:%M:%S'在远程机器文件上

时间:2017-08-16 09:23:57

标签: python csv datetime remote-access paramiko

我使用sftp在远程计算机上打开一个文件,它工作正常,但我收到了这个错误

ValueError: time data '"2015-06-25 14:50:00"' does not match format 
'%Y-%m-%d %H:%M:%S'

但我使用的格式是正确的。这是代码各部分的代码。

#!/usr/bin/env python
# -*-coding:utf-8 -*
import os
import sys
import time
import stat
import pysftp as sftp
import subprocess
import paramiko
import datetime
from datetime import datetime, timedelta
from time import mktime, strftime, localtime, sleep



u_name = 'robi'
pswd = 'xxxx'
port = 22
r_ip = 'xxx.xxx.x.xxx'
sec_key = '/home/rob/key_detail'

myconn = paramiko.SSHClient()
myconn.set_missing_host_key_policy(paramiko.AutoAddPolicy())
my_rsa_key = paramiko.RSAKey.from_private_key_file(sec_key)
session = myconn.connect(r_ip, username=u_name, password=pswd, port=port,
                         pkey=my_rsa_key)
# print myconn.get_transport().is_active()
# path1 = "/home/rob_remote/sensors/12/tem_data/temp.dat"
fmt = '%Y-%m-%d %H:%M:%S'
path1 = "/home/rob_remote/sensors/12/tem_data/temp.dat"
path2 = '/home/new/loc/13/press/pressure.dat'
start_time = datetime.strptime("2015-06-25 14:50:00", fmt)
latest_time = datetime.now()
step_size = 10
diff = latest_time - start_time
minutes_values = diff.total_seconds() / 60
expected = int(minutes_values / step_size)
sftp = myconn.open_sftp()
with sftp.open(path1) as f:
    read = f.readlines()[4:]
    get_values = []
    for line in read:
        line = line.strip().split(',')
        start_date = line[0]
        start_date = datetime.strptime(start_date, fmt)
        current_time = datetime.now()
        step_size = 5
        differ_time = current_time - start_date
        minutes_values = differ_time.total_seconds() / 60
        get_values.append(int(minutes_values / step_size))
    # print 'get_values:::::::::::::::::::', max(get_values)
get_val = max(get_values)
.
.
.
.

有人可以帮助我或指导我处理这个问题。我会很感激的。

1 个答案:

答案 0 :(得分:1)

看起来您的日期字符串用双引号括起来,您可以在格式字符串中包含双引号,或者更简单的方法是首先删除它们:

In[15]:
d = '"2015-06-25 14:50:00"'.replace('"','')
datetime.strptime(d, fmt)

Out[15]: datetime.datetime(2015, 6, 25, 14, 50)

strip也可以在这里工作:

d.strip('\"')

所以在你的代码中添加这个

start_date = line[0].replace('"','')

start_date = line[0].strip('\"')