0

我现在正在使用 Python 进行编程,这是我的第一个项目。任何帮助,将不胜感激。

我最近从 Rainforest 获得了一个可以读取我的电表的设备。该装置有一个可通过 USB 访问的 USB 端口。我设法将设备连接到我的 Raspberry Pi 并从串行端口中提取一个十六进制字符串。目前该字符串正在读取 0x18f0cb39。我需要获取这个数字并将其转换为正确的格式并将其输出为时间和日期。我正在编程的设备手册位于http://www.rainforestautomation.com/sites/default/files/download/rfa-z106/raven_xml_api_r127.pdf

在将时代转换为时间和日期时,我很困惑。我把#'s放在有困难的行前面。

我写的代码是:

#!/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

在此先感谢您的帮助

斯科特

4

2 回答 2

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 年,所以我一定做错了什么,但也许这会让您朝着正确的方向或提示迈出一步别人为你写一个更好的答案。

于 2013-04-12T03:57:10.180 回答
0

根据 Rainforest RAVEn XML API 文档,对您的 GetTime 请求的 TimeCluster 响应说明了数据格式:

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 日的 Rainforest 纪元转换为 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 时间对象之间进行转换。)

于 2013-04-29T22:05:42.550 回答