# -*- coding: UTF-8 -*-
"""
現在時刻取得
get_ntp_now.py
開発環境:
Raspberry Pi Pico W
Micropython
2025/03 : Ver.0.1 初版
Copyright 2025 Moo Soft(Yokoyama Akiyosi)
ntptime : https://github.com/micropython/micropython-lib/blob/master/micropython/net/ntptime/ntptime.py
time.gmtime([secs]) time.localtime([secs])
secs にはエポック(上記を参照)からの秒数で表される時間をします。
この指定の時間を8項目のタプル
(year, month, mday, hour, minute, second, weekday, yearday)
に変換します。
secs を与えないか None である場合は RTC の現在時間を使います。
8項目のタプルのフォーマットは次のとおりです:
year: 西暦の年(たとえば 2025)
month: 月を表す 1-12
mday: 日を表す 1-31
hour: 時を表す 0-23
minute: 分を表す 0-59
second: 秒を表す 0-59
weekday: 月曜-日曜を表す 0-6
yearday: 年内の通算日数を表す 1-366
"""
import ntptime
import utime
import time
import network
import machine
# ============================================== #
# 0 パディング
# s : 元の文字列
# width : 文字数
# ============================================== #
def zfill(s, width):
if len(s) < width:
return ("0" * (width - len(s))) + s
else:
return s
# def zfill(s, width)
# ============================================== #
# 現在日時取得
# 戻り値 : 日時文字列
# ============================================== #
def get_now():
#wday = ["Mon","Tue","Wed","Thu","Fri","Sat","Sun"]
wday = ["月","火","水","木","金","土","日"]
#ntptime.host = "ntp.nict.jp" # NTP サーバー設定
# 初期値 : https://www.ntppool.org/ja/
t = ntptime.time()
t = t + 9*60*60 # JP
dttuple = time.gmtime(t)
print(dttuple)
dttuple = time.localtime()
print(dttuple)
year = str(dttuple[0])
month = zfill(str(dttuple[1]), 2)
mday = zfill(str(dttuple[2]), 2)
hour = zfill(str(dttuple[3]), 2)
minute = zfill(str(dttuple[4]), 2)
seconds = zfill(str(dttuple[5]), 2)
w_index = dttuple[6]
#日付と時刻を分けるデリミター("|")を付加
datetime = year + "/" + month + "/" + mday + "(" + wday[w_index] + ")|" + hour + ":" + minute + ":" + seconds
return datetime
# def get_now():
# ============================================== #
# Wi-Fi 接続
# ============================================== #
def con_wifi():
ssid = "SSID" # SSID
pas = "PASSWD" # パスワード
led = machine.Pin("LED", machine.Pin.OUT) # LED
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, pas)
max_wait = 10
while max_wait > 0:
led.value(0)
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
print("waiting for connection...")
time.sleep(1)
led.value(1)
time.sleep(1)
if wlan.status() != 3:
raise RuntimeError("network connection failed")
else:
print("Connected")
status = wlan.ifconfig()
print("ip = " + status[0])
# con_wifi()
# ============================================== #
# メイン
# ============================================== #
def main():
con_wifi()
datetime = get_now()
print(datetime)
while True:
now = get_now()
now_array = now.split("|") #日付と時刻は2行に分けて表示
print(now_array[0])
print(now_array[1])
utime.sleep(60)
# def main():
# ============================================== #
if __name__=="__main__":
main()
コメントを残す