【问题标题】:How to convert it back to datetime format?如何将其转换回日期时间格式?
【发布时间】:2018-01-05 12:56:23
【问题描述】:

我想对日期执行算术运算,所以我转换了这些日期

idx_1 = 2017-06-07 00:00:00
idx_2 = 2017-07-27 00:00:00 

使用浮动,

x1 = time.mktime(idx_1.timetuple())  # returns float of dates
>>> 1496773800.0
x2 = time.mktime(idx_2.timetuple())
>>> 1501093800.0
y1 = 155.98
y2 = 147.07

我使用下面的代码来绘制:

    import datetime as dt
    import time
    import numpy as np
    import matplotlib.pyplot as plt
    x = [x1, x2]
    y = [y1, y2]
    Difference = x2 - x1 #this helps to end the plotted line at specific point
    coefficients = np.polyfit(x, y, 1)
    polynomial = np.poly1d(coefficients)
    # the np.linspace lets you set number of data points, line length.
    x_axis = np.linspace(x1, x2 + Difference, 3)  # linspace(start, end, num)
    y_axis = polynomial(x_axis)
    plt.plot(x_axis, y_axis)
    plt.plot(x[0], y[0], 'go')
    plt.plot(x[1], y[1], 'go')
    plt.show()

哪些情节:

如何让 matplotlib 在 x 轴上绘制实际日期而不是浮点数?

非常感谢任何形式的帮助。

【问题讨论】:

    标签: python datetime numpy matplotlib


    【解决方案1】:

    从 datetime 对象开始,您可以使用 matplotlib 的 date2numnum2date 函数在数值之间进行转换。这样做的好处是,matplotlib.dates 定位器和格式化程序可以理解数字数据。

    import datetime
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.dates
    
    idx_1 = datetime.datetime(2017,06,07,0,0,0)
    idx_2 = datetime.datetime(2017,07,27,0,0,0)
    
    idx = [idx_1, idx_2]
    
    y1 = 155.98
    y2 = 147.07
    
    x = matplotlib.dates.date2num(idx)
    y = [y1, y2]
    Difference = x[1] - x[0] #this helps to end the plotted line at specific point
    coefficients = np.polyfit(x, y, 1)
    polynomial = np.poly1d(coefficients)
    # the np.linspace lets you set number of data points, line length.
    x_axis = np.linspace(x[0], x[1] + Difference, 3)  # linspace(start, end, num)
    y_axis = polynomial(x_axis)
    plt.plot(x_axis, y_axis)
    plt.plot(x[0], y[0], 'go')
    plt.plot(x[1], y[1], 'go')
    
    loc= matplotlib.dates.AutoDateLocator()
    plt.gca().xaxis.set_major_locator(loc)
    plt.gca().xaxis.set_major_formatter(matplotlib.dates.AutoDateFormatter(loc))
    plt.gcf().autofmt_xdate()
    plt.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-05
      • 2019-09-03
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 2012-08-03
      • 1970-01-01
      相关资源
      最近更新 更多