我现在用Python编程,这是我的第一个项目。任何帮助将不胜感激。
我最近从雨林中获得了一个可以读取电表的设备。该装置有一个可通过USB访问的USB端口。我设法将设备挂钩到我的Raspberry Pi并从串口中提取十六进制字符串。目前该字符串正在读取0x18f0cb39。我需要取这个数字并将其转换为正确的格式并将其输出为时间和日期。我正在编程的设备手册是http://www.rainforestautomation.com/sites/default/files/download/rfa-z106/raven_xml_api_r127.pdf
当谈到将时代转换为时间和日期时,我感到非常困惑。我把#放在有困难的线前面。
我写的代码是:
#!/usr/bin/env python
import serial
import time
serial.port = serial.Serial("/dev/ttyUSB0", 115200, timeout=0.5)
serial.port.write("<Command><Name>get_time</Name><Refresh>N</Refresh></Command>")
response=serialport.readline(none)
response=serialport.readline(none)
response=serialport.readline(none)
response=serialport.readline(none)
response=serialport.readline(none)
myString=response[13:23]
#struct_time = int(raw_input(((myString >> 40) +1970, (ts >> 32 & 0xFF) +1, ts >> 24 & 0xFF, ts>> 16)))
#thetime=time.strftime("%7-%m-%d-%H-%M-%s)
print myString
提前感谢您的帮助
斯科特
答案 0 :(得分:0)
查看文档,我不明白你是如何使用切片13:23从TimeCluster响应中获取你的时间(以十六进制),但你的问题的主旨和你注释掉的代码似乎如何将0x18f0cb39转换为本地日期和时间?
>>> import time
>>> help(time)
(output snipped, but this is so handy....)
>>> t = 0x18f0cb39
>>> time.ctime(t)
'Tue Apr 5 15:37:29 1983'
>>> time.localtime(t)
time.struct_time(tm_year=1983, tm_mon=4, tm_mday=5, tm_hour=15, tm_min=37, tm_sec=29, tm_wday=1, tm_yday=95, tm_isdst=0)
既然你在6天前发布了你的问题而今天是11日,那个答案中的日期似乎已经过了30年,所以我一定做错了,但也许这会让你在右边迈出一步方向或提示别人为你写一个更好的答案。
答案 1 :(得分:0)
根据Rainforest RAVEn XML API文档,TimeCluster对GetTime请求的响应说明了数据格式:
TimeCluster notifications provide the current time reported on the
meter in both UTC and Local time. The time values are the number of
seconds since 1-Jan-2000 UTC.
正如您所猜测的那样,Python时间是自1970年1月1日以来的秒数。所以你可以从2000年1月1日的雨林时代转换到像这样的Python时代:
myString=response[13:23]
seconds_since_2000 = int(myString, 16)
# compute number of seconds between 1-Jan-1970 and 1-Jan-2000
delta = calendar.timegm(time.strptime("2000-01-01", "%Y-%m-%d"))
time.ctime(seconds_since_2000 + delta)
(注意:以上内容仅供参考。在生产系统中,您可能希望编写一个专用函数来转换RAVEn生成的原始十六进制文本和python时间对象。)