Python模块更改系统日期和时间
如何在Python中更改系统日期、时间和时区?是否有任何模块可用于此Python模块更改系统日期和时间,python,date,time,Python,Date,Time,如何在Python中更改系统日期、时间和时区?是否有任何模块可用于此 我不想执行任何系统命令 我想要一个通用的解决方案,它应该可以在Unix和Windows上运行 现在我认为这是最好的解决办法 import sys,os def change(s): if s == 1:os.system('date -s "2 OCT 2006 18:00:00"')#don't forget to change it , i've used date command for linux e
现在我认为这是最好的解决办法
import sys,os
def change(s):
if s == 1:os.system('date -s "2 OCT 2006 18:00:00"')#don't forget to change it , i've used date command for linux
elif s == 2:
try:
import pywin32
except ImportError:
print 'pywin32 module is missing'
sys.exit(1)
pywin32.SetSystemTime(year, month , dayOfWeek , day , hour , minute , second , millseconds )# fill all Parameters with int numbers
else:print 'wrong param'
def check_os():
if sys.platform=='linux2':change(1)
elif sys.platform=='win32':change(2)
else:print 'unknown system'
现在这只是一个临时解决方案,希望能有所帮助,请看一看
我没有windows机器,所以我没有在windows上测试它。。。但是你明白了。我不得不稍微修改一下win32版本的tMC的答案:
def _win_set_time(time_tuple):
import win32api
dayOfWeek = datetime(*time_tuple).isocalendar()[2]
t = time_tuple[:2] + (dayOfWeek,) + time_tuple[2:]
win32api.SetSystemTime(*t)
例如,当我使用它根据旧的时间服务器(时间协议,RFC868)设置时间时,我大致是这样做的:
data = s.recv(4)
remote_time = (ord(data[0])<<24) + (ord(data[1])<<16) + (ord(data[2])<<8) + ord(data[3])
remote_time -= 2208988800
_win_set_time(time.gmtime(remote_time)[0:6] + (0,))
data=s.recv(4)
remote_time=(ord(数据[0])tMC的答案似乎很好。但是,它对我来说并不正常。我发现它需要一些更新,适用于Linux和Windows+python 3。下面是我更新的模块:
import sys
from _datetime import datetime
time_tuple = (2012, # Year
9, # Month
6, # Day
0, # Hour
38, # Minute
0, # Second
0, # Millisecond
)
def _win_set_time(time_tuple):
import win32api
dayOfWeek = datetime(*time_tuple).isocalendar()[2]
t = time_tuple[:2] + (dayOfWeek,) + time_tuple[2:]
win32api.SetSystemTime(*t)
def _linux_set_time(time_tuple):
import subprocess
import shlex
time_string = datetime(*time_tuple).isoformat()
subprocess.call(shlex.split("timedatectl set-ntp false")) # May be necessary
subprocess.call(shlex.split("sudo date -s '%s'" % time_string))
subprocess.call(shlex.split("sudo hwclock -w"))
if sys.platform == 'linux2' or sys.platform == 'linux':
_linux_set_time(time_tuple)
elif sys.platform == 'win32':
_win_set_time(time_tuple)
对于Linux,请阅读以下答案:这对我很有用
- 自动转换为UTC时间
- 将字符串转换为日期时间
- 使用日期时间输入
- 它更具可读性
查看>>给定系统权限和身份验证,这比您认为的Unix和Windows更难做到。@EngHamoud,我不认为datetime
模块可以设置系统时间。以下是在和中进行设置的一些方法。@benhoyt:正确……datetime在这种情况下没有用处……感谢这两种解决方案……但我需要d两个平台都有一个组合解决方案。因此,这不符合我的要求。@Blender:感谢再次教育我:-)我不想浪费时间编写我自己的,如果可以使用的话。。如果系统是linux,这当然会创建一个子进程来运行date
system命令。OP不想做的事情。从datetime导入datetime中错过,否则在安装pywin32Use后工作使用如果sys.platform.startswith('linux')
要使用Python>=3.3。根据@jk987的回答,正确的模块名称是win32api
,而不是pywin32
。另外,SetSystemTime
接受8个参数;您可以添加*
,也可以执行remote\u time=datetime.datetime.fromtimstamp(response.tx\u time)+datetime.datetime.utcnow()-datetime.datetime.now()
然后执行win32api.SetSystemTime(remote\u time.year,remote\u time.month,remote\u time.isoweekday()),remote_time.day,remote_time.hour,remote_time.minute,remote_time.second,remote_time.microsecond//1000)
。干得好!但是datetime.datetime()接受微秒,而不是毫秒,因此您应该乘以1000而不是1000000才能将它们转换为纳秒。请注意,从python 3.3开始,可以使用python函数简化此代码的linux部分,而不是使用ctypes调用系统库。如上所述,datetime.datetime()似乎接受微秒,而不是毫秒,所以你应该乘以1000而不是1000000才能将它们转换为纳秒。@daghemo你是什么意思?我在哪里繁殖?请忘了我吧:也许意大利CODIV-19的社会距离让我发疯了(您似乎使用datetime.isoformat()来转换日期并将其传递给date命令,因此这里没有乘法运算(上面的例子就是使用它的)。请记住,时间元组中的最后一个0只保留几微秒,而不是几毫秒。仅此而已。这不是真正的错误。:)您正在执行系统命令,而OP明确要求您避免这样做。
import sys
from _datetime import datetime
time_tuple = (2012, # Year
9, # Month
6, # Day
0, # Hour
38, # Minute
0, # Second
0, # Millisecond
)
def _win_set_time(time_tuple):
import win32api
dayOfWeek = datetime(*time_tuple).isocalendar()[2]
t = time_tuple[:2] + (dayOfWeek,) + time_tuple[2:]
win32api.SetSystemTime(*t)
def _linux_set_time(time_tuple):
import subprocess
import shlex
time_string = datetime(*time_tuple).isoformat()
subprocess.call(shlex.split("timedatectl set-ntp false")) # May be necessary
subprocess.call(shlex.split("sudo date -s '%s'" % time_string))
subprocess.call(shlex.split("sudo hwclock -w"))
if sys.platform == 'linux2' or sys.platform == 'linux':
_linux_set_time(time_tuple)
elif sys.platform == 'win32':
_win_set_time(time_tuple)
def _win_set_time(datetime_obj: datetime):
import win32api
# http://timgolden.me.uk/pywin32-docs/win32api__SetSystemTime_meth.html
# win32api.SetSystemTime(year, month , dayOfWeek , day , hour , minute , second , millisecond )
utc_datetime = datetime_obj.astimezone().astimezone(timezone.utc).replace(tzinfo=None)
day_of_week = utc_datetime.isocalendar()[2]
win32api.SetSystemTime(utc_datetime.year, utc_datetime.month, day_of_week,
utc_datetime.day, utc_datetime.hour, utc_datetime.minute, utc_datetime.second,
int(utc_datetime.microsecond / 1000))
real_time_str = "2020 12 24 13 11 10 321"
real_time = datetime.strptime(real_time_str, '%Y %m %d %H %M %S %f')
_win_set_time(real_time)