2012-08-24 137 views
1

我想使用下面的代碼來設置系統日期(而不是時間)。我想將當前時間設置爲新的日期。以下是示例代碼,我發現更改後時間不正確。在Python中,使用win32api沒有設置正確的日期

day = 20 
month = 3 
year = 2010 

timetuple = time.localtime() 
print timetuple 
print timetuple[3], timetuple[4], timetuple[5] 
win32api.SetSystemTime(year, month, timetuple[6]+1, 
    day, timetuple[3], timetuple[4], timetuple[5], 1) 

回答

4

您正在設置localtime時間戳的系統時間。後者根據當地時區進行調整,而SetSystemTimerequires you to use the UTC timezone

使用time.gmtime()代替:

tt = time.gmttime() 
win32api.SetSystemTime(year, month, 0, day, 
    tt.tm_hour, tt.tt_min, tt.tt_sec, 0) 

然後,您也避免對付你是否是在夏令時間(DST),現在,與3月份的時候,你會在冬天的時候。

或者您可以使用一個datetime.datetime.utcnow() call並得到毫秒參數作爲獎金:

import datetime 
tt = datetime.datetime.utcnow().time() 
win32api.SetSystemTime(year, month, 0, day, 
    tt.hour, tt.minute, tt.second, tt.microsecond//1000) 

注意,我離開了平日的項目在這兩個例子中設置爲0;撥打SetSystemTime時將忽略它。如果它是而不是忽略,那麼你的代碼示例的值是錯誤的;週一到週日的Python值範圍爲0到6,而Win32 API需要從1到7的週日到週六。您必須添加2並使用模7:

win32_systemtime_weekday = (python_weekday + 2) % 7) 
+1

這需要使用提升的權限運行,因爲普通用戶無權訪問以更改系統時間。 –

+0

@BurhanKhalid:顯然這不是問題;爲OP設定了錯誤的時間。 –

+2

是的,但值得澄清。 –

相關問題