January 30, 2026
time 模块示例
本文档介绍 time 模块的时间转换与延时功能。示例来源:doc/pikapython.com/examples/time/time_test1.py。
模块简介
time 模块提供 localtime、mktime、sleep/sleep_ms 等。内嵌示例:
import time
time.sleep_ms(500) # 延时 500 毫秒
tm = time.localtime()
print(tuple(tm))
示例代码
localtime 与 mktime(time_test1.py)
import time
tm = time.localtime()
print(tm)
print(tuple(tm))
assert tuple(time.localtime(1719905967)) == (2024, 7, 2, 15, 39, 27, 1, 184, 0)
assert tuple(time.localtime(1519905963)) == (2018, 3, 1, 20, 6, 3, 3, 60, 0)
assert tuple(time.localtime(1919105967)) == (
2030, 10, 25, 4, 59, 27, 4, 298, 0)
assert time.mktime((2024, 7, 2, 15, 39, 27, 1, 184, 0)) == 1719905967
assert time.mktime((2018, 3, 1, 20, 6, 3, 3, 60, 0)) == 1519905963
assert time.mktime((2030, 10, 25, 4, 59, 27, 4, 298, 0)) == 1919105967
print('PASS')
说明:localtime([timestamp]) 将时间戳转为 9 元组(年、月、日、时、分、秒、星期、一年中第几天、夏令时);mktime(tuple) 将 9 元组转为时间戳。设备上若无可选时间源,localtime() 无参形式可能返回默认或零值。
注意事项
- 嵌入式设备上时间戳可能依赖 RTC 或网络对时,未配置时结果可能为 0 或固定值。
sleep/sleep_ms以实际平台实现为准。