こんばんわ!Keisukeです!
今日は,インターネットからPython経由でデータを取得してみたいと思います!
ntp.NTPCクライアントから日本時刻の時間を取得してみたいと思います!
※NTPC : 国立研究発注法人 情報通信研究機構
まずはライブラリのインストール
pip install ntplib
コード
import datetime
from time import ctime
import sys
import ntplib
#時刻を取得
# object
#NTPサーバー名
#日本 : ntp.nict.jp
#アメリカ : ntp.nasa.gov
class MyNTPClient(object):
def __init__(self, ntp_server_host):
self.ntp_client = ntplib.NTPClient()
self.ntp_server_host = ntp_server_host
def get_nowtime(self, timeformat = ‘%Y/%m/%d %H:%M:%S’):
try:
#サーバーへデータ取得依頼
res = self.ntp_client.request(self.ntp_server_host)
nowtime = datetime.datetime.strptime(ctime(res.tx_time), “%a %b %d %H:%M:%S %Y”)
return nowtime.strftime(timeformat)
#エラー
except Exception as e:
print(“An error occured”)
print(“The information of error is as following”)
print(type(e))
print(e.args)
print(e)
sys.exit(1)
if __name__ == “__main__”:
ntp_client = MyNTPClient(‘ntp.nict.jp’)
print(ntp_client.get_nowtime())
実行結果
2018/08/15 23:30:06
上記のデータをJSON形式で表示してみたいと思います1
import datetime
from time import ctime
import sys
import ntplib
import json
class MyNTPClient(object):
def __init__(self, ntp_server_host):
self.ntp_client = ntplib.NTPClient()
self.ntp_server_host = ntp_server_host
def get_nowtime(self, timeformat = ‘%Y/%m/%d %H:%M:%S’):
data = []
try:
res = self.ntp_client.request(self.ntp_server_host)
nowtime = datetime.datetime.strptime(ctime(res.tx_time), “%a %b %d %H:%M:%S %Y”)
data.append(ctime(res.tx_time)[0:3])
data.append(‘year’)
data.append(ctime(res.tx_time)[20:25])
data.append(‘month’)
data.append(ctime(res.tx_time)[4:7])
data.append(‘day’)
data.append(ctime(res.tx_time)[8:10])
data.append(‘hour’)
data.append(ctime(res.tx_time)[11:13])
data.append(‘minutes’)
data.append(ctime(res.tx_time)[14:17])
data.append(‘secound’)
data.append(ctime(res.tx_time)[17:19])
return nowtime.strftime(timeformat),data
except Exception as e:
print(“An error occured”)
print(“The information of error is as following”)
print(type(e))
print(e.args)
print(e)
sys.exit(1)
if __name__ == “__main__”:
ntp_client = MyNTPClient(‘ntp.nict.jp’)
print(ntp_client.get_nowtime())
実行結果
(‘2018/08/22 11:09:04’,
[‘Wed’,
‘year’, ‘2018’,
‘month’, ‘Aug’,
‘day’, ’15’,
‘hour’, ’00’,
‘minutes’, ’10’,
‘secound’, ’23’])
もう少しうまく書きたいなぁ…
人のコードを見て勉強します!
※追記 8/23
自分でいろいろ工夫してみました!
import ntplib
from time import ctime
import json
if __name__ == ‘__main__’:
c = ntplib.NTPClient()
response = c.request(‘pool.ntp.org’)
s = ctime(response.tx_time)
t = s.split()
t_json = {}
t_json[t[0]] = {“year ” : int(t[4]),”month” : t[1],”day ” : int(t[2]),”time ” : t[3]}
print(t_json)
json_t = json.dumps(t_json,indent=4)
print(json_t,’\n’)
#f = open(‘time_JP.json’,’a’)
f = open(‘time_JP.json’,’w’)
f.write(json_t)
f.write(‘\n’)
f.close()
実行結果
{‘Thu’: {‘year ‘: 2018, ‘month’: ‘Aug’, ‘day ‘: 23, ‘time ‘: ’09:59:21’}}
{
“Thu”: {
“year “: 2018,
“month”: “Aug”,
“day “: 23,
“time “: “09:59:21”
}
}
見やすくなった!
[今日の達成]
・日本時刻を取得する
[今日の未消化]
・コードをすっきり書く