5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

pythonでntpclientを利用して時刻取得

Last updated at Posted at 2017-10-13

やりたいこと

ntpプロトコルで時刻を取得のみしたい(同期は不要)

ntpdate コマンドで、ntpdate -qで時刻同期はせずに取得できるものの、
日付 月 時刻 で年が表示されなかったことと、時刻以外の情報も表示されていて、bashで解析するのは少し難しい...

ntpのプロトコルがあるってことは、クライアントのサンプルとかあるんじゃ?と思って調べてみたら、大好きなpythonでntplibという
モジュールの中にntplib.NTPClientとどんぴしゃであった!

試した環境

  • Ubuntu 14.04
  • Python 3.6.2

ntplibのインストール

pip使ってインストール!

$ (sudo) pip install ntplib

ソースについて

ntplib.NTPCLIENTで、インスタンス生成
そして、request(ntpservername)でntpサーバへ問い合わせ
ctime(res.tx_time)にて、いったんctime形式でパースしたものを
datetime型に変換

これで日付型で扱えるので、あとは煮るなり焼くなりするだけ
今回は自分が求めるフォーマットでprintしてます。
gitにも同じコード挙げてます

最初の投稿時ではclass化もしておらず、エラー処理もなかったのですが、
class化 + エラー処理を付け加えました。
また出力フォーマットも引数で柔軟に対応できるようにしてます。

https://github.com/komorin0521/python_sandbox/tree/master/python3

ソース(v.1.1.0): 2017年10月14日更新

# !/usr/bin/env python3

import datetime
from time import ctime
import sys

# please install module using pip-
# (sudo) pip install ntp lib
import ntplib

__author__ = "oomori"
__version__ = "1.2.0"

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)

def main():
    ntp_client = MyNTPClient('ntp.nict.jp')
    print(ntp_client.get_nowtime())

if __name__ == "__main__":
    main()

参考

5
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?