【问题标题】:Plotting time on the x-axis with Python's matplotlib使用 Python 的 matplotlib 在 x 轴上绘制时间
【发布时间】:2019-11-16 20:03:32
【问题描述】:

我正在从包含格式数据(日期时间;微伏)的文本文件中读取数据:

例如07.03.2017 23:14:01,000; 279

我希望使用 matplotlib 通过仅捕获时间(x 轴)并将其与微伏(y 轴)进行绘制来绘制图表。到目前为止,我已经设法从字符串中提取时间元素并将其转换为 datetime 格式(如下所示)。

我试图将每个时间值附加到 x 中以进行绘图,但程序只是冻结并且什么也不显示。

下面是部分代码:

from datetime import datetime
import matplotlib.pyplot as plt


ecg = open(file2).readlines()

x = []
for line in range(len(ecg)):
    ecgtime = ecg[7:][line][:23]
    ecgtime = datetime.strptime(ecgtime, '%d.%m.%Y %H:%M:%S,%f')
    x.append(ecgtime.time())

我知道日期时间格式会导致问题,但我不知道如何将其转换为浮点/整数,因为它说:

'float() 的无效文字:23:14:01,000'

【问题讨论】:

    标签: python datetime matplotlib time graph


    【解决方案1】:

    我没有评论的声誉,我必须回答。

    datetime.datetime.time() 转换为 datetime.time 对象,你需要浮点数。
    你能试试datetime.datetime.timestamp()吗?

    见最后一行:

    from datetime import datetime
    import matplotlib.pyplot as plt
    
    ecg = open(file2).readlines()
    
    x = []
    for line in range(len(ecg)):
        ecgtime = ecg[7:][line][:23]
        ecgtime = datetime.strptime(ecgtime, '%d.%m.%Y %H:%M:%S,%f')
        x.append(ecgtime.timestamp())
    

    编辑:timestamp() 在 Python 3.3 中可用。对于 Python 2,您可以使用

    from time import mktime
    ...
        x.append(mktime(ecgtime.timetuple()))
    

    【讨论】:

    • 嗨 rysson,我刚试过,但它给了我:AttributeError: 'datetime.datetime' object has no attribute 'timestamp'
    • 函数datetime.datetime.timetamp是3.3版的新功能。对于老年人,您需要使用 time.mktime(ecgtime.timetuple())。
    猜你喜欢
    • 2019-04-17
    • 2022-08-08
    • 2012-03-26
    • 2020-09-18
    • 2023-03-31
    相关资源
    最近更新 更多