如何将其转换回日期时间格式? [英] How to convert it back to datetime format?

查看:105
本文介绍了如何将其转换回日期时间格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I wanted to perform arithmetic operations on dates so i converted these dates

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

Am使用以下代码进行绘制:

Am using the following code to plot:

    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轴上绘制实际日期而不是浮点数?

How to make matplotlib to plot the actual dates on x axis instead of floats?

非常感谢任何帮助.

推荐答案

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

Starting with datetime objects you may use matplotlib's date2num and num2date functions to convert to and from numerical values. The advantage is that the numerical data is then understood by matplotlib.dates locators and formatters.

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()

这篇关于如何将其转换回日期时间格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆