Python, how can I print the current datetime on the same line as a text message?
-
13-10-2019 - |
Question
First experiences with Python here, I want to be able to print out some text with the current time/date as the first item on the line.
This is what I've been able to cook up so far, but it appears I'm syntactically incorrect, can someone please correct me?
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()
Kind regards
Solution
I think you're looking for something like
print "%d %d closed" % (now_text, remote_port)
For future reference, here's one way to do that in Python 3:
print("{0} {1} closed".format(now_text, remote_port))
The .format()
method was introduced in Python 2.6.
OTHER TIPS
Two possible errors (the second one definite):
Exception,e
needs to be replaced byException as e
(depending on the Python version).- The % operator requires a tuple argument:
"%d %d closed" % (a, b)
.
>>> print "%s %d closed " % (now_text,remote_port)
2011-03-15 14:46 9002 closed
This is my take:
#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))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow