将字节字符串转换为matplotlib可读tim

2024-09-30 03:24:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我在youtube上看了一个python教程,有一集是关于使用字节字符串数据在matplotlib中绘制的,但是我没有权限访问视频中使用的数据,所以我在google上搜索了如何创建一个,但是感觉kianda不对。我不知道我是否找到了创建字节字符串数据的正确方法,视频中使用的函数在我的程序中无法运行。 代码如下:

def bytespdate2num(fmt,encoding='UTF-8'):
    strconverter = mdates.strpdate2num(fmt)
    def bytesconverter(b):
        s = b.decode(encoding)
        return strconverter(s)
    return bytesconverter

c = b'19970108'
a = bytespdate2num('%Y%m%d')
print(a(c))

所以我得到的结果是b=729032.0

我想我还没有完全理解代码是如何被利用的。请随时指出我做错了什么。谢谢各位!!!在


Tags: 数据字符串代码视频return字节youtubematplotlib
1条回答
网友
1楼 · 发布于 2024-09-30 03:24:23

从你在问题中显示的情况来看,代码是正确的。输入字符串c = b'19970108',得到输出729032.0。此输出以matplotlib使用的数字日期时间格式表示1997年8月1日。在

您可以通过

print(mdates.num2date(a(c)))
# this prints 1997-01-08 00:00:00+00:00

看看它能起作用。在

要绘制输出,基本上有3个选项。在

  • 仅仅使用plot当然会显示数字(matplotlib如何知道它应该绘制日期?)。在

    ^{pr2}$

    enter image description here

  • 使用plot_date()

     plt.plot_date( a(c), 1, marker="d")
    

    enter image description here

  • 使用mdates.num2date转换为datetime

    plt.plot( mdates.num2date(a(c)), 1, marker="d")
    

    enter image description here

  • 使用定位器和格式化程序

    plt.plot( a(c), 1, marker="d")
    loc = mdates.AutoDateLocator()
    plt.gca().xaxis.set_major_locator(loc)
    plt.gca().xaxis.set_major_formatter(mdates.AutoDateFormatter(loc))
    

    enter image description here 最后一种方法允许最大的灵活性,因为您也可以使用其他定位器和格式化程序。请参见matplotlib.dates API或{a6}。

相关问题 更多 >

    热门问题