python-3.x - 声明并填充 time.struct_time 类型变量
问题描述
!嗨伙计!我正在尝试将从 I2C 连接的 RTC 获得的 bcd 编码日期时间数据转换为time.struct_time
以后可以将其用作本机类型。RTC 返回一个数组,应该在使用之前对其进行解码。源代码是这样的:
import time
...
def bcd2dec(bcd):
return(10 * (bcd >> 4) + (bcd & 0x0F))
...
rtcdata = [36, 54, 35, 48, 35, 36, 32] # BCD coded datetime from RTC
rtc_time = time.struct_time(
tm_year = bcd2dec(rtcdata[6]),
tm_mon = bcd2dec(rtcdata[5] & 0x1F), # last 5 bits
tm_mday = bcd2dec(rtcdata[3] & 0x3F), # last 6 bits
tm_hour = bcd2dec(rtcdata[2] & 0x3F), # last 6 bits
tm_min = bcd2dec(rtcdata[1] & 0x7F), # last 7 bits
tm_sec = bcd2dec(rtcdata[0] & 0x7F), # last 7 bits
tm_wday = bcd2dec(rtcdata[4] & 0x07) # last 3 bits
)
但这不起作用。我花了几个小时试图弄清楚如何在没有运气的情况下填充这个“命名元组”。有人可以建议热声明这样的变量并用他们的名字填充所有相应的属性吗?
解决方案
经过几个小时的痛苦挣扎和互联网搜索后,我能够编写一个解决方案。但实际上我发现只使用rtc_time = time.struct_time(())
解决方案更具可读性。可能这会帮助某人。
import time
from collections import namedtuple
...
def bcd2dec(bcd):
return(10 * (bcd >> 4) + (bcd & 0x0F))
...
struct_time_ = namedtuple('struct_time', ['tm_year', 'tm_mon', 'tm_mday', 'tm_hour', 'tm_min', 'tm_sec', 'tm_wday', 'tm_yday', 'tm_isdst'])
rtcdata = [36, 54, 35, 48, 35, 36, 32] # BCD coded datetime from RTC
rtc_time = struct_time_(
tm_sec = bcd2dec(rtcdata[0] & 0x7F), # last 7 bits
tm_min = bcd2dec(rtcdata[1] & 0x7F), # last 7 bits
tm_hour = bcd2dec(rtcdata[2] & 0x3F), # last 6 bits
tm_mday = bcd2dec(rtcdata[3] & 0x3F), # last 6 bits
tm_wday = bcd2dec(rtcdata[4] & 0x07), # last 3 bits
tm_mon = bcd2dec(rtcdata[5] & 0x1F), # last 5 bits
tm_year = bcd2dec(rtcdata[6]),
tm_yday = 0,
tm_isdst = -1
)
推荐阅读
- java - Selenium Java 代理错误
- java - Netty:如何在没有任何标头/字段指示长度的服务器上接收可变长度消息
- ocaml - 告诉 omake 使用静态版本的 ac 库
- python - 如何使用 Python 脚本通过 SSH 访问文件?
- reactjs - 如何在 JavaScript 中测试包含 fetch 调用的部分代码
- python - 检查哪个 conda env jupyter 控制台正在使用
- json - 在组件之间传递数据:React JS
- sql - PostgreSQL - 如何使用窗口函数从列中提取最大值
- php - 没有为 [voyager] 定义提示路径
- python - 如何在tensorflow中找到给定.ckpt.meta文件的输出节点名称