问题
For my centralized logging purposes for an application that will be used over the network(no server side application involved, yet) I am required to also store the time at which a particular event occurs. The task is pretty much easy but the problem is, as I have noticed, the computers over the network don't have their time setup accurately. Therefore in order to standardize the time I choose to grab it from the NAS using net time \\nas. All's good to this point.
Now the problem is, the format in which net time
returns the time is dependent on the the particular system's datetime format, on which the application is run, which is guaranteed to be consistent, and therefore rendering a hard coded dateformat conversion to timestamp useless. Any solutions and opinions?
Can't use this solution since I am coding in python.
回答1:
The output I was getting from net time \\nas
is in the following format:
Current time at \\nas is dd/mm/yyyy HH:MM:SS
Local time (GMT) at \\nas is dd/mm/yyyy HH:MM:SS
The command completed successfully.
The following approach got me what I needed:
import subprocess
import time
import datetime
from _winreg import *
from dateutil.parser import parse
def runProcess(exe):
p = subprocess.Popen(exe, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
while(True):
retcode = p.poll() #returns None while subprocess is running
line = p.stdout.readline()
yield line
if(retcode is not None):
break
def nasTime():
for line in runProcess(r"net time \\nas".split()):
timeLine = line
break
timeLine = timeLine.split("is ")[1].replace("\r\n", "")
hKey = OpenKey (HKEY_CURRENT_USER, r"Control Panel\International")
value, type = QueryValueEx (hKey, "sShortDate")
dayFirst = str(value).lower().startswith("d") # tells if day first format was being used
return time.mktime(parse(timeLine, dayfirst = dayFirst).timetuple())
Code stolen from here(runProcess
) and one other place I can't recall.
来源:https://stackoverflow.com/questions/16729279/how-to-determine-what-date-time-format-the-system-is-using