需求:
server端:接收时间戳时间,转换成格式化时间
client端:每隔10秒中把时间戳发给server端,time.time()
1、时间格式转换模块time_convert.py
模块说明:
导入time模块,定义时间戳转成格式化时间(字符串时间)的函数custom_time(timestamp) ,因为time.localtime(secs) ,参数secs支持float类型,所以要判断函数custom_time(timestamp)中timestamp参数是否是float类型,如果不是需要转换timestamp参数类型为float类型,然后通过time.localtime(timestamp)把时间戳转换成结构化时间time_local,再通过time.strftime('%Y-%m-%d %H:%M:%S',time_local)把结构化时间time_local转换成格式化时间dt,并通过return 返回dt,到此时间格式转换完成。
import time'''时间戳转格式化时间(字符串时间)'''def custom_time(timestamp): if type(timestamp) == 'float': time_local = time.localtime(timestamp) dt = time.strftime('%Y-%m-%d %H:%M:%S',time_local) else: timestamp = float(timestamp) time_local = time.localtime(timestamp) dt = time.strftime('%Y-%m-%d %H:%M:%S', time_local) return dt
2、服务端代码:
import socketimport time_convert #导入时间格式转换模块server = socket.socket()ip_port = ('0.0.0.0',8001)server.bind(ip_port)server.listen()conn,addr = server.accept()while 1: from_client_msg = conn.recv(1024) client_time = from_client_msg.decode('utf-8') print(time_convert.custom_time(client_time)) #调用时间格式转换方法conn.close()server.close()
3、客户端代码:
import timeimport socketclient = socket.socket()ip_port = ('127.0.0.1',8001)client.connect(ip_port)while 1: client_msg = str(time.time()) #获取当前时间戳,并转换数据类型为字符串 str1 = client.send(bytes(client_msg.encode('utf-8'))) #编码发送数据 print(client_msg) time.sleep(5)