python根据网络时间修改本地时间

简介

由于本人电脑时间经常错误,于是编写了此代码,以方便修改时间。
如有不足之处,请指正。

code

import subprocess
import logging
from datetime import datetime
import http.client
import time

class System_Time:

    def __init__(self):
        self.__newtime = None

    @property
    def newtime(self):
        return self.__newtime

    @newtime.setter
    def newtime(self, value):
        self.__newtime = value

    def get_sys_now_time(self):
        return datetime.strftime(datetime.now(),"%H:%M:%S")

    def get_webservertime(self, host='www.baidu.com'):
        conn = http.client.HTTPConnection(host)
        conn.request("GET", "/")
        r = conn.getresponse()
        # r.getheaders() #获取所有的http头
        ts = r.getheader('date')  # 获取http头date部分
        # 将GMT时间转换成北京时间
        ltime = time.strptime(ts[5:25], "%d %b %Y %H:%M:%S")
        # print(ltime)
        ttime = time.localtime(time.mktime(ltime) + 8 * 60 * 60)
        # print(ttime)
        dat = "%u-%02u-%02u" % (ttime.tm_year, ttime.tm_mon, ttime.tm_mday)
        tm = "%02u:%02u:%02u" % (ttime.tm_hour, ttime.tm_min, ttime.tm_sec)
        # print("dat:{}".format(dat))
        print("tm:{}".format(tm))
        return tm

    @classmethod
    def alter(cls):
        obj = cls()
        webtm = obj.get_webservertime()
        obj.newtime = webtm
        # print(obj.newtime)
        try:
            ps = subprocess.Popen(
                'time',
                universal_newlines=True,
                shell=True,
                stdout=subprocess.PIPE,
                stdin=subprocess.PIPE
            )

            ps.communicate(obj.newtime, 15)
            logging.basicConfig(level=logging.NOTSET)
            if ps.poll() is not None:
                logging.info("进程成功终止")
            else:
                logging.warning("进程未终止")

            if ps.returncode == 0:
                logging.info("系统时间修改成功")
            elif ps.returncode > 0:
                logging.warning("进程异常:{}".format(ps.returncode))
            elif ps.returncode < 0 or ps.returncode > 10000:
                logging.error("进程错误")
        except Exception as error:
            print(error.__str__())


if __name__ == '__main__':
    System_Time.alter()

运行结果示例:

在这里插入图片描述
)

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值