使用strftime命令聚合year:month:date的语法

时间:2016-09-08 05:04:22

标签: python-3.x strftime

我从系统使用datetime获取当前时间并将其存储为字符串(timenow),但是当我通过sshclient_exec_command将其发送到linux中时,会有一些行为差异。

以下是我的代码:

timenow = datetime.datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")
command = 'date -s %s' %timenow
stdin, stdout, stderr = self._sshclient.exec_command(command, timeout=10)
try:
    command = 'date +"%Y-%m-%d %H:%M:%S"'
    stdin, stdout, stderr = self._sshclient.exec_command(command, timeout=10)
    ip_time_now = stdout.read().decode(encoding='UTF-8').rstrip('\n')
    self.logger.debug(" ip=%s timenow=%s ip_time_now=%s",ip, timenow,ip_time_now)

输出

 timenow=2016-09-07 20:15:26 ip_time_now=2016-09-07 21:06:24

timenow和ip_time_now都应该与操作

相同

如果我用

替换timenow行
timenow = datetime.datetime.utcnow().strftime("%H:%M:%S")  #passes, but without 
                                                      setting the year and month

输出

timenow=20:25:49 ip_time_now=2016-09-07 20:25:50 #1 sec diff is ok

注意:执行命令时输出中没有异常

strftime语法的可能解决方案是什么?

1 个答案:

答案 0 :(得分:1)

更换

command = 'date -s %s' %timenow

command = 'date --set "%s"' %timenow

将解决。