How can I change System Date, Time, Timezone in Python? Is there any module available for this?
- I don’t want to execute any system commands
- I want one common solution, which should work on both Unix and Windows.
Advertisement
Answer
JavaScript
x
57
57
1
import sys
2
import datetime
3
4
time_tuple = ( 2012, # Year
5
9, # Month
6
6, # Day
7
0, # Hour
8
38, # Minute
9
0, # Second
10
0, # Millisecond
11
)
12
13
def _win_set_time(time_tuple):
14
import pywin32
15
# http://timgolden.me.uk/pywin32-docs/win32api__SetSystemTime_meth.html
16
# pywin32.SetSystemTime(year, month , dayOfWeek , day , hour , minute , second , millseconds )
17
dayOfWeek = datetime.datetime(time_tuple).isocalendar()[2]
18
pywin32.SetSystemTime( time_tuple[:2] + (dayOfWeek,) + time_tuple[2:])
19
20
21
def _linux_set_time(time_tuple):
22
import ctypes
23
import ctypes.util
24
import time
25
26
# /usr/include/linux/time.h:
27
#
28
# define CLOCK_REALTIME 0
29
CLOCK_REALTIME = 0
30
31
# /usr/include/time.h
32
#
33
# struct timespec
34
# {
35
# __time_t tv_sec; /* Seconds. */
36
# long int tv_nsec; /* Nanoseconds. */
37
# };
38
class timespec(ctypes.Structure):
39
_fields_ = [("tv_sec", ctypes.c_long),
40
("tv_nsec", ctypes.c_long)]
41
42
librt = ctypes.CDLL(ctypes.util.find_library("rt"))
43
44
ts = timespec()
45
ts.tv_sec = int( time.mktime( datetime.datetime( *time_tuple[:6]).timetuple() ) )
46
ts.tv_nsec = time_tuple[6] * 1000000 # Millisecond to nanosecond
47
48
# http://linux.die.net/man/3/clock_settime
49
librt.clock_settime(CLOCK_REALTIME, ctypes.byref(ts))
50
51
52
if sys.platform=='linux2':
53
_linux_set_time(time_tuple)
54
55
elif sys.platform=='win32':
56
_win_set_time(time_tuple)
57
I don’t have a windows machine so I didn’t test it on windows… But you get the idea.