ビジネスパーソン・ガジェット置場 empty lot for business

営業や仕事、それに伴う生活を便利に楽にするツール、ガジェットを作ります。既にあるツールも自分用にカスタマイズ。

【自動】潮位情報取得

毎日、決まった時間に潮位情報を自動で取得しデータを更新するガジェット

(難易度★★★)

f:id:kslabo51:20220217211230j:plain

★こんな感じのガジェットです★

API提供サイトからデータを定期的に自動で取得しスプレッドシートに記入

f:id:kslabo51:20220218214839p:plain

必要な設定

■データ: 日本沿岸736港の潮汐表 

■プログラム言語:Python

■ライブラリ:requests, pandas, datetime, gspread, oauth2client

■その他:

 

手順① 取得した情報をスプレッドシートで管理するため、スプレッドシートの作成。

今回、築地(東京)と三田尻(山口)の二つの港について潮位情報を取得してみます。スプレッドシートには、それぞれの港ごとにシートを作成し、取得したい項目をA列に設定しました。B列以降で日付と潮位情報を日々取得して追加していきます。

 

f:id:kslabo51:20220217213030p:plain

※上記は既に3日分のデータを取得済みのものになります。

 

手順② GCPでプロジェクトの作成と鍵の取得等各種設定を行う。

arachnes-web.hatenablog.jp

手順③ コード作成

コードは下記のようになります。

※auth関数の'あなたのスプレッドシートのID'は使用するスプレッドシートのurl

https://docs.google.com/spreadsheets/d/この部分になります/edit#gid=

 

import requests
import pandas as pd
import datetime as dt
import gspread
from oauth2client.service_account import ServiceAccountCredentials

def auth():
    SP_CREDENTIAL_FILE = 'secret.json'
    SP_SCOPE = [
        'https://spreadsheets.google.com/feeds',
        'https://www.googleapis.com/auth/drive'
    ]

    SP_SHEET_KEY = 'あなたのスプレッドシートのID'
    SP_SHEET1 = 'tukiji'
    SP_SHEET2 = 'mitajiri'

    credentials = ServiceAccountCredentials.from_json_keyfile_name(SP_CREDENTIAL_FILE, SP_SCOPE)
    gc = gspread.authorize(credentials)

    worksheet1 = gc.open_by_key(SP_SHEET_KEY).worksheet(SP_SHEET1)
    worksheet2 = gc.open_by_key(SP_SHEET_KEY).worksheet(SP_SHEET2)
    return worksheet1, worksheet2


def main():
    tide_url = 'https://api.tide736.net/get_tide.php'

    today = dt.date.today().strftime('%Y-%m-%d')
    year = dt.date.today().year
    month = dt.date.today().month
    day = dt.date.today().day

    worksheet1, worksheet2 = auth()
    df_tukiji = pd.DataFrame(worksheet1.get_all_records())
    df_mitajiri = pd.DataFrame(worksheet2.get_all_records())

    pc = [13, 35]
    hc = [1, 11]

    for i, j in zip(pc, hc):
        params = {
            'pc': i,
            'hc': j,
            'yr': f'{year}',
            'mn': f'{month}',
            'dy': f'{day}',
            'rg': 'day'
        }

        res = requests.get(tide_url, params)
        info = res.json()

        tide_port = info['tide']['port']
        tide_chart = info['tide']['chart'][today]

        port_name = tide_port['harbor_namej']
        yobina = tide_chart['moon']['name']
        shio = tide_chart['moon']['title']
        if len(tide_chart['flood']) == 1:
            mancho1 = tide_chart['flood'][0]['time']
            mancho_height1 = tide_chart['flood'][0]['cm']
            mancho2 = '-'
            mancho_height2 = '-' 
        else:
            mancho1 = tide_chart['flood'][0]['time']
            mancho_height1 = tide_chart['flood'][0]['cm']
            mancho2 = tide_chart['flood'][1]['time']
            mancho_height2 = tide_chart['flood'][1]['cm']
        if len(tide_chart['edd']) == 1:
            kancho1 = tide_chart['edd'][0]['time']
            kancho_height1 = tide_chart['edd'][0]['cm']
            kancho2 = '-'
            kancho_height2 = '-'
        else:
            kancho1 = tide_chart['edd'][0]['time']
            kancho_height1 = tide_chart['edd'][0]['cm']
            kancho2 = tide_chart['edd'][1]['time']
            kancho_height2 = tide_chart['edd'][1]['cm']
        hinode = tide_chart['sun']['rise']
        hinoiri = tide_chart['sun']['set']
        tukide = tide_chart['moon']['rise'].split(' ')[1]
        tukiiri = tide_chart['moon']['set'].split(' ')[1]

        if i == pc[0]:
            df_tukiji[today] = [port_name, yobina, shio, mancho1, mancho_height1, 
                                mancho2, mancho_height2, kancho1, kancho_height1, 
                                kancho2, kancho_height2 ,hinode, hinoiri, tukide, tukiiri]
        else:
            df_mitajiri[today] = [port_name, yobina, shio, mancho1, mancho_height1, 
                                mancho2, mancho_height2, kancho1, kancho_height1, 
                                kancho2, kancho_height2 ,hinode, hinoiri, tukide, tukiiri]

    worksheet1.update([df_tukiji.columns.values.tolist()] + df_tukiji.values.tolist())
    worksheet2.update([df_mitajiri.columns.values.tolist()] + df_mitajiri.values.tolist())


if __name__ =='__main__':
    main()

〜

手順⑤ Automaterとカレンダーの設定

記載したコードを定期実行させる方法についてはこちらから

arachnes-web.hatenablog.jp


今後の展開

  • APIで時間ごとのデータも提供されているので水位のグラフを作成し可視化
  • streamlitなど使用しWebアプリケーションで手軽にチェックできるようにする

など