繁体   English   中英

Python,我如何在文本消息的同一行上打印当前日期时间?

[英]Python, how can I print the current datetime on the same line as a text message?

这里是Python的初体验,我希望能够以当前时间/日期作为第一行打印出一些文本。

到目前为止,这是我能够做的事情,但是看来我在语法上不正确,有人可以纠正我吗?

import socket
import sys
import time
import datetime

remote_host = "127.0.0.1"

now = datetime.datetime.now()

for remote_port in [9002,8080]:
        now_text = now.strftime("%Y-%m-%d %H:%M")
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(60)
        try:
                sock.connect((remote_host, remote_port))
        except Exception,e:
                print "%d %d closed " % now_text remote_port
        else:
                print  "%d %d open" % now_text remote_port
        sock.close()

亲切的问候

我认为您正在寻找类似的东西

print "%d %d closed" % (now_text, remote_port)

供以后参考,这是在Python 3中执行此操作的一种方法:

print("{0} {1} closed".format(now_text, remote_port))

.format()方法是Python 2.6中引入的。

两个可能的错误(第二个是确定的):

  1. Exception,e需要由Exception as e替换Exception as e (取决于Python版本)。
  2. %运算符需要一个元组参数: "%d %d closed" % (a, b)

这是我的看法:

#the code below will print the date and time on separate lines.

from datetime import datetime
now =datetime.now()

print('%s/%s/%s' %(now.month,now.day,now.year))
print('%s:%s:%s' %(now.hour,now.minute,now.second))
>>> print "%s %d closed " % (now_text,remote_port)
2011-03-15 14:46 9002 closed

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM