演示日期转换

演示日期转换示例

  1. import datetime
  2. import matplotlib.pyplot as plt
  3. from matplotlib.dates import DayLocator, HourLocator, DateFormatter, drange
  4. import numpy as np
  5. date1 = datetime.datetime(2000, 3, 2)
  6. date2 = datetime.datetime(2000, 3, 6)
  7. delta = datetime.timedelta(hours=6)
  8. dates = drange(date1, date2, delta)
  9. y = np.arange(len(dates))
  10. fig, ax = plt.subplots()
  11. ax.plot_date(dates, y ** 2)
  12. # this is superfluous, since the autoscaler should get it right, but
  13. # use date2num and num2date to convert between dates and floats if
  14. # you want; both date2num and num2date convert an instance or sequence
  15. ax.set_xlim(dates[0], dates[-1])
  16. # The hour locator takes the hour or sequence of hours you want to
  17. # tick, not the base multiple
  18. ax.xaxis.set_major_locator(DayLocator())
  19. ax.xaxis.set_minor_locator(HourLocator(range(0, 25, 6)))
  20. ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
  21. ax.fmt_xdata = DateFormatter('%Y-%m-%d %H:%M:%S')
  22. fig.autofmt_xdate()
  23. plt.show()

下载这个示例