用于更改系统日期和时间的 Python 模块

标签 python date time

如何在 Python 中更改系统日期、时间、时区?有没有可用的模块?

  1. 我不想执行任何系统命令
  2. 我想要一个通用的解决方案,它应该适用于 Unix 和 Windows。

最佳答案

import sys
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 pywin32
    # http://timgolden.me.uk/pywin32-docs/win32api__SetSystemTime_meth.html
    # pywin32.SetSystemTime(year, month , dayOfWeek , day , hour , minute , second , millseconds )
    dayOfWeek = datetime.datetime(time_tuple).isocalendar()[2]
    pywin32.SetSystemTime( time_tuple[:2] + (dayOfWeek,) + time_tuple[2:])


def _linux_set_time(time_tuple):
    import ctypes
    import ctypes.util
    import time

    # /usr/include/linux/time.h:
    #
    # define CLOCK_REALTIME                     0
    CLOCK_REALTIME = 0

    # /usr/include/time.h
    #
    # struct timespec
    #  {
    #    __time_t tv_sec;            /* Seconds.  */
    #    long int tv_nsec;           /* Nanoseconds.  */
    #  };
    class timespec(ctypes.Structure):
        _fields_ = [("tv_sec", ctypes.c_long),
                    ("tv_nsec", ctypes.c_long)]

    librt = ctypes.CDLL(ctypes.util.find_library("rt"))

    ts = timespec()
    ts.tv_sec = int( time.mktime( datetime.datetime( *time_tuple[:6]).timetuple() ) )
    ts.tv_nsec = time_tuple[6] * 1000000 # Millisecond to nanosecond

    # http://linux.die.net/man/3/clock_settime
    librt.clock_settime(CLOCK_REALTIME, ctypes.byref(ts))


if sys.platform=='linux2':
    _linux_set_time(time_tuple)

elif  sys.platform=='win32':
    _win_set_time(time_tuple)

我没有 windows 机器,所以我没有在 windows 上测试它......但你明白了。

关于用于更改系统日期和时间的 Python 模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12081310/

相关文章:

python - python中的三向字典深度合并

python - 使用 Wordpresslib 编辑 WordPress 帖子

python - For numpy/pandas 循环(迭代列标题)

excel - 公式丢失日期格式

java - 时间:下周五怎么过?

Gitlab CI 中的 Python 覆盖率未显示任何百分比

date - Gson setDateFormat 在日期为空时抛出异常

linux - 用于在 Linux 中的所有子文件夹中使用正确的日期格式重命名文件名的 Bash 脚本

python - 在Python脚本中处理时间命令的输出

c++ - 如何从 std::chrono::system_clock::time_point.time_since_epoch().count() 获取 std::chrono::system_clock::time_point?