How would you find the time offset between the local OS system-time and Internet time from various Internet time sources using Python?
Use ntplib. Right from the manual:
>>> import ntplib
>>> c = ntplib.NTPClient()
>>> response = c.request('europe.pool.ntp.org', version=3)
>>> response.offset
-0.143156766891
Just to save you some time. Here's the code I ended up with using phihag's answer. It prints the drift every interval_sec to screen and to a log file.
You'll need to easy_install ntplib for it to work.
import logging
logging.basicConfig(filename='time_shift.txt',level=logging.DEBUG)
import ntplib
import time
import datetime
c = ntplib.NTPClient()
interval_sec = 60
while True:
try:
response = c.request('europe.pool.ntp.org', version=3)
txt = '%s %.3f' % (datetime.datetime.now().isoformat(), response.offset)
print txt
logging.info(txt)
except:
pass
time.sleep(interval_sec)
Related
i want to get the utc time directly from a website that can give that. and i don't want to use python modules because they give me the system time and my system time does not show the correct time.
how can i get the correct utc time without changing the system time?
i use
import ntplib,datetime
x = ntplib.NTPClient()
datetime.datetime.utcfromtimestamp(x.request('europe.pool.ntp.org').tx_time)
but i get this error
raise NTPException("No response received from %s." % host)
ntplib.NTPException: No response received from europe.pool.ntp.org.
Could you try to call datetime.utcnow()? From the python docs
Here is my output
>>> import datetime
>>> datetime.datetime.utcnow()
datetime.datetime(2018, 11, 4, 9, 47, 59, 572104)
Edit as OP having issues with above
As for a web based solution, this works fine for me (Whilst avoiding your website
>>> import requests
>>> x = requests.get('http://worldtimeapi.org/api/timezone/Europe/London.txt')
>>> print(x.content)
b'abbreviation: GMT\ndatetime: 2018-11-04T10:09:18.395273+00:00\nday_of_week: 0\nday_of_year: 308\ndst: false\ndst_from: \ndst_until: \ntimezone: Europe/London\nunixtime: 1541326158\nutc_offset: +00:00\nweek_number: 44'
Update
You can get the datetime like so. I am certain there is a better way to do this, but this method works fine for this specific use-case.
>>> import requests
>>> x = requests.get('http://worldtimeapi.org/api/timezone/Europe/London.txt')
>>> y = x.text
>>> print(y[27:47])
2018-11-04T11:01:46
Struggling with what is I am sure a very straight forward problem. I have a scheduled task set up which launches a batch file, which in turn runs a Python script. All is well, however I cannot seem to close the Python shell once the script is finished. The result is lots of open windows.
If this is a Python issue, I have read the best way to close is to do the following:
import selenium
import json
import time
import datetime
import sys
from selenium import webdriver
from datetime import timedelta
today = datetime.datetime.today()
yesterday = today - timedelta(days=1)
yesterday = yesterday.strftime("%d.%m.%Y")
browser = webdriver.Chrome(executable_path = 'c:/xampp/htdocs/portal/functions/timon/chromedriver.exe')
browser.get('http://adventures.timon.is')
time.sleep(2)
browser.find_element_by_id('tbxNumerstarfsmanns').clear()
browser.find_element_by_id('tbxNumerstarfsmanns').send_keys('user')
browser.find_element_by_id('tbxUserLykilord').clear()
browser.find_element_by_id('tbxUserLykilord').send_keys('pass')
time.sleep(2)
browser.find_element_by_css_selector('input[type=\"submit\"]').click()
browser.find_element_by_css_selector("a[href*=reports]").click()
browser.find_element_by_link_text("Salary administrators").click()
browser.find_element_by_link_text("Punch-in report").click()
time.sleep(2)
browser.find_element_by_id('id_fromdate').clear()
browser.find_element_by_id('id_fromdate').send_keys(yesterday)
browser.find_element_by_id('id_todate').clear()
browser.find_element_by_id('id_todate').send_keys(yesterday)
time.sleep(2)
browser.find_element_by_css_selector("input[type=submit]").click()
time.sleep(2)
results = browser.find_elements_by_css_selector("table#resultstable td")
columns = [val.text for val in results]
data = json.dumps(columns)
text_file = open("c:/xampp/htdocs/portal/functions/timon/info.txt", "w")
text_file.write(data)
text_file.close()
browser.close()
sys.exit()
However this does not work.
Batch file looks like this...
start "extractTimon" "C:\xampp\Python36-32\python.exe" C:\xampp\htdocs\portal\functions\timon\extractTimon.py
If anyone could point me in the right direction, I'd really appreciate it.
I want to put a list into my threading script, but I am facing a problem.
Contents of list file (example):
http://google.com
http://yahoo.com
http://bing.com
http://python.org
My script:
import codecs
import threading
import sys
import requests
from time import time as timer
from timeout import timeout
import time
try:
with codecs.open(sys.argv[1], mode='r', encoding='ascii', errors='ignore') as iiz:
iiz=iiz.read().splitlines()
except IOError:
pass
oz = list(iiz)
def nnn(url):
hzz = {'param1': sys.argv[2], 'param2': sys.argv[3]}
po = requests.post(url,data=hzz)
if po:
print("ok \n")
if __name__ == '__main__':
threads = []
for i in range(1):
t = threading.Thread(target=nnn, args=(oz,))
threads.append(t)
t.start()
Can you please clarify what elaborate on exactly what you're trying to achieve.
I'm guessing that you're trying to request urls to load into a web browser or the terminal...
Also you shouldn't need to put the urls into a list because when you opened up the file containing the urls, it automatically sorted it into a list. So in other words, the contents in iiz are already in the list format.
Personally, I haven't worked much with the modules you're using (apart from time), but I'll try my best to help you and hopefully other users will try and help you too.
I'm trying to write a simple program to print the current date with Python 3.4. In the shell, I can import datetime, and use now() but when I write a script with a class it fails and gives this error:
"AttributeError: module object has no attribute now".
Can anyone help explain the problem? This is my code:
import datetime
class Date:
def __init__(self, filename):
self.writeToFile(filename)
def date(self):
now = datetime.datetime.now()
return now
def writeToFile(self, filename):
date = self.date()
file = open(filename, 'w')
file.write(date)
for i in range(20): # simply test for writting in file
file.write(str(i)+'\t')
file.close()
return file
d = Date('datetime.txt')
import datetime
datetime.datetime.now()
Make sure you are importing the intended datetime module, and it is not being overridden by local files with same name. you can check it with:
import datetime
print(datetime.__file__)
and check the output if it is pointing to the correct directory you want.
I had this error too and all I did was
Import datetime
from datetime import datetime
# then u can declare ur variable let's say something like
today = datetime.datetime.now()
#u can add what ever u want
#the point is make sure u do the datetime.datetime.now()
print(today)
What I'm trying to do is upload a picture to wordpress using wp.uploadFile xmlrpc method.
To do this, in PHP there is an example here: https://stackoverflow.com/a/8910496/1212382
I'm trying to do the same thing in python but I don't know how.
Anyone any ideas?
ok, the answer lies in the xmlrpclib class.
To send base64 bits to wordpress from python you need to use the xmlrpclib class like so:
base64bits = xmlrpclib.Binary(file_content)
then you just add the base64bits variable to the 'bits' parameter in your wp.uploadFile xmlrpc request.
to be a little more exact, here's the complete code in python of how this should be done:
import xmlrpclib
import urllib2
from datetime import date
import time
def get_url_content(url):
try:
content = urllib2.urlopen(url)
return content.read()
except:
print 'error! NOOOOOO!!!'
file_url = 'http://the path to your picture'
extension = file_url.split(".")
leng = extension.__len__()
extension = extension[leng-1]
if (extension=='jpg'):
xfileType = 'image/jpeg'
elif(extension=='png'):
xfileType='image/png'
elif(extension=='bmp'):
xfileType = 'image/bmp'
file = get_url_content(file_url)
file = xmlrpclib.Binary(file)
server = xmlrpclib.Server('http://website.com/xmlrpc.php')
filename = str(date.today())+str(time.strftime('%H:%M:%S'))
mediarray = {'name':filename+'.'+extension,
'type':xfileType,
'bits':file,
'overwrite':'false'}
xarr = ['1', 'USERHERE', 'PASSWORDHERE', mediarray]
result = server.wp.uploadFile(xarr)
print result