Raspberry Pi 3b Add python time synchronization script

Source: Internet
Author: User
Tags local time python script

The Raspberry Pi does not have a battery, so the system time stops after the power outage, until you start the timer again.

Because the project needs to use local time, the accuracy requirements are not high do not want to toss (if you need high precision, need to install NTP), so consider using Python script synchronization Baidu time, accuracy error is small in 0.5-1 seconds, need network support.

1. Create a Python program

sudo nano date.py

2. Write Python code

#-*-coding:utf-8-*-ImportOSImport TimeImportHttplib#get remote server time and synchronize localdefGet_webservertime (host): Conn=Httplib. Httpconnection (host) conn.request ("GET","/") R=conn.getresponse () TS= R.getheader ('Date')#gets the HTTP header date partLtime= Time.strptime (ts[5:25],"%d%b%Y%h:%m:%s")#convert GMT time to Beijing timeTtime=time.localtime (Time.mktime (ltime) +8*60*60)#time zone + 8 hoursCurrenttime="%u-%02u-%02u%02u:%02u:%02u"%(ttime.tm_year,ttime.tm_mon,ttime.tm_mday,ttime.tm_hour,ttime.tm_min,ttime.tm_sec) Os.system ('sudo date-s "'+ CurrentTime +'"') Time.sleep (20) Get_webservertime ("www.baidu.com") while1: Time.sleep (120) Get_webservertime ("www.baidu.com")

3. Giving permission

sudo chmod 777 date.py

4. Test procedure

Change the system time to an expiration time first

' 2016-02-03 10:00:00 '

To see if the system time has been modified successfully

sudo date

Execute a well-written Python program and use the date command after 20 seconds to see if the system time is synchronized successfully!

sudo python date.py

5. Add Python program to boot

Edit the system startup file

sudo nano/etc/rc.local

Add a script before exit 0 (note the program path)

/usr/bin/python/home/pi/date.py >/home/pi/getdate.log

6, restart the Raspberry Pi, after 20 seconds to check whether the system time synchronization success

sudo reboot

Raspberry Pi 3b Add python time synchronization script

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.