首页 > 解决方案 > 声明并填充 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
)

但这不起作用。我花了几个小时试图弄清楚如何在没有运气的情况下填充这个“命名元组”。有人可以建议热声明这样的变量并用他们的名字填充所有相应的属性吗?

标签: python-3.x

解决方案


经过几个小时的痛苦挣扎和互联网搜索后,我能够编写一个解决方案。但实际上我发现只使用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
)

推荐阅读