LoginSignup
0
0

ntpを使わずに時間を合わせてみた

Last updated at Posted at 2024-04-29

Pythonを使用してAPIから取得した日時情報でシステムの日付と時刻を設定する方法

背景

学校のセキュリティー関係でntpサーバに接続できなかった(なんでや).なので,毎回sudo date --set "2024-04-29 09:03:54"のようにraspberrypiの日時を更新していたのだが,流石に面倒なので,APIサーバーから日時を取得して時間を合わせるようにしてみた.

コード

以下のコードを適当なディレクトリに保存し,.bashrcやら.zshrcpython3 ~/hogehoge.pyのように書けば,起動時に勝手に実行してくれると思います.

import requests
import subprocess

# APIエンドポイント
url = "https://www.timeapi.io/api/Time/current/zone?timeZone=Asia/Tokyo"

# リクエストを送信してレスポンスを取得
response = requests.get(url)

# レスポンスのステータスコードを確認
if response.status_code == 200:
    # JSON形式のレスポンスデータを取得
    data = response.json()

    # 取得したデータを使用してシステムの日付と時刻を設定するコマンドを生成
    command = f"sudo date --set \"{data['year']}-{str(data['month']).zfill(2)}-{str(data['day']).zfill(2)} {str(data['hour']).zfill(2)}:{str(data['minute']).zfill(2)}:{str(data['seconds']).zfill(2)}\""

    # サブプロセスを使用してコマンドを実行
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, error = process.communicate()

    # コマンドが正常に実行されたかどうかを確認
    if process.returncode == 0:
        print("コマンドが正常に実行されました。")
        print(output.decode())
    else:
        print("コマンドの実行中にエラーが発生しました:", error.decode())
else:
    print("データの取得に失敗しました:", response.status_code)

終わりに

同じように困っている人(多分いない)の参考になればと思います.間違え等ございましたら,コメントで教えていただけるとありがたいです.

0
0
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
0
0