# -*- coding: utf-8 -*-
import ctypes
import time
import datetime
CLOCK_REALTIME = 0
class timespec(ctypes.Structure):
_fields_ = [
('tv_sec', ctypes.c_long), # 秒
('tv_nsec', ctypes.c_long), # 纳秒(1 ms = 1,000,000 ns)
]
# 加载 libc
librt = ctypes.CDLL('librt.so.1', use_errno=True)
clock_settime = librt.clock_settime
clock_settime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)]
# 获取当前时间并加 1100 毫秒
now = datetime.datetime.now() + datetime.timedelta(milliseconds=1100)
# 构造 timespec 结构体
ts = timespec()
ts.tv_sec = int(time.mktime(now.timetuple()))
ts.tv_nsec = (now.microsecond * 1000) # 微秒转纳秒
# 调用 clock_settime 设置时间
if clock_settime(CLOCK_REALTIME, ctypes.byref(ts)) != 0:
import ctypes.util
errno = ctypes.get_errno()
print(u"❌ 设置系统时间失败,错误代码:%d,原因:%s" % (errno, os.strerror(errno)))
else:
print(u"✅ 系统时间已成功设置为(毫秒级):%s.%03d" % (now.strftime("%Y-%m-%d %H:%M:%S"), now.microsecond // 1000))
Linux通过python脚本设置系统时间(毫秒)
技术分享 ·
# -*- coding: utf-8 -*- import ctypes import time import datetime CLOCK_REALTIME = 0 class timespec(ctypes.Structure): _fields_ = [ ('tv_sec', ctypes.c_long), …
- Linux