0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Pythonライブラリを使って、日出・日没時間を取得する

Posted at

はじめに

 天文学を扱うPythonライブラリであるPyEphemを使って、Pythonで日出時間および日没時間を取得する方法を紹介する。また、応用例として昼夜判定方法も併せて紹介する。

動作確認環境

  • OS
    • Windows 10
    • Ubuntu 20.04
  • Python
    • 3.8.10
    • 3.10.11

環境構築

 pipでpyephemをインストールする。

pip install pyephem

方法

日出時間、日没時間の取得

 現時刻に対する日出時間、日没時間を計算する。

#!/usr/bin/env python

import ephem
import datetime

observer = ephem.Observer()

# 東京駅の緯度経度
observer.lat = '35.6809591'
observer.lon = '139.7673068'

# 現在時刻 (UTC)
observer.date = datetime.datetime.utcnow()

sun = ephem.Sun()

# UTC時刻で、日出・日没時間を取得
prev_sunrise_utc_date = observer.previous_rising(sun, use_center=True)
next_sunrise_utc_date = observer.next_rising(sun, use_center=True)
prev_sunset_utc_date = observer.previous_setting(sun, use_center=True)
next_sunset_utc_date = observer.next_setting(sun, use_center=True)

# ローカル時刻へ変換
current_local_date = ephem.localtime(observer.date)
prev_sunrise_local_date = ephem.localtime(prev_sunrise_utc_date)
next_sunrise_local_date = ephem.localtime(next_sunrise_utc_date)
prev_sunset_local_date = ephem.localtime(prev_sunset_utc_date)
next_sunset_local_date = ephem.localtime(next_sunset_utc_date)


print(f'現在時刻:{current_local_date}')
print(f'現在時刻より前の日の出時刻:{prev_sunrise_local_date}')
print(f'現在時刻より後の日の出時刻:{next_sunrise_local_date}')
print(f'現在時刻より前の日の入り時刻:{prev_sunset_local_date}')
print(f'現在時刻より後の日の入り時刻:{next_sunset_local_date}')

出力例

現在時刻:2024-11-26 06:16:20.814236
現在時刻より前の日の出時刻:2024-11-25 06:28:02.656880
現在時刻より後の日の出時刻:2024-11-26 06:29:00.191108
現在時刻より前の日の入り時刻:2024-11-25 16:27:30.708754
現在時刻より後の日の入り時刻:2024-11-26 16:27:11.204736

昼夜判定

 上記の日出時間、日没時間の取得のPythonコードに以下を追記する。

is_night = False
# 太陽が出ているかどうかを判定
if prev_sunrise_local_date > prev_sunset_local_date:
    print('Sun is up')

    if (prev_sunrise_local_date < current_local_date < next_sunset_local_date):
        is_night = False
    else:
        is_night = True

# 太陽が沈んでいるかどうかを判定
else:
    print('Sun is down')
    if (prev_sunset_local_date < current_local_date < next_sunrise_local_date):
        is_night = True
    else:
        is_night = False

print(f'現時刻({current_local_date})は、' + ('' if is_night else ''))

出力例

Sun is down
2024-11-26 06:16:20.814236は、夜

まとめ

 Pythonで日出時間および日没時間を取得する方法を紹介した。また、応用例として昼夜判定方法を紹介した。夜間に自動で照明を点灯したい場合などに有用である。

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?