test_dates.py 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975
  1. import datetime
  2. import dateutil.tz
  3. import dateutil.rrule
  4. import functools
  5. import numpy as np
  6. import pytest
  7. from matplotlib import rc_context
  8. import matplotlib.dates as mdates
  9. import matplotlib.pyplot as plt
  10. from matplotlib.testing.decorators import image_comparison
  11. import matplotlib.ticker as mticker
  12. def test_date_numpyx():
  13. # test that numpy dates work properly...
  14. base = datetime.datetime(2017, 1, 1)
  15. time = [base + datetime.timedelta(days=x) for x in range(0, 3)]
  16. timenp = np.array(time, dtype='datetime64[ns]')
  17. data = np.array([0., 2., 1.])
  18. fig = plt.figure(figsize=(10, 2))
  19. ax = fig.add_subplot(1, 1, 1)
  20. h, = ax.plot(time, data)
  21. hnp, = ax.plot(timenp, data)
  22. np.testing.assert_equal(h.get_xdata(orig=False), hnp.get_xdata(orig=False))
  23. fig = plt.figure(figsize=(10, 2))
  24. ax = fig.add_subplot(1, 1, 1)
  25. h, = ax.plot(data, time)
  26. hnp, = ax.plot(data, timenp)
  27. np.testing.assert_equal(h.get_ydata(orig=False), hnp.get_ydata(orig=False))
  28. @pytest.mark.parametrize('t0', [datetime.datetime(2017, 1, 1, 0, 1, 1),
  29. [datetime.datetime(2017, 1, 1, 0, 1, 1),
  30. datetime.datetime(2017, 1, 1, 1, 1, 1)],
  31. [[datetime.datetime(2017, 1, 1, 0, 1, 1),
  32. datetime.datetime(2017, 1, 1, 1, 1, 1)],
  33. [datetime.datetime(2017, 1, 1, 2, 1, 1),
  34. datetime.datetime(2017, 1, 1, 3, 1, 1)]]])
  35. @pytest.mark.parametrize('dtype', ['datetime64[s]',
  36. 'datetime64[us]',
  37. 'datetime64[ms]',
  38. 'datetime64[ns]'])
  39. def test_date_date2num_numpy(t0, dtype):
  40. time = mdates.date2num(t0)
  41. tnp = np.array(t0, dtype=dtype)
  42. nptime = mdates.date2num(tnp)
  43. np.testing.assert_equal(time, nptime)
  44. @pytest.mark.parametrize('dtype', ['datetime64[s]',
  45. 'datetime64[us]',
  46. 'datetime64[ms]',
  47. 'datetime64[ns]'])
  48. def test_date2num_NaT(dtype):
  49. t0 = datetime.datetime(2017, 1, 1, 0, 1, 1)
  50. tmpl = [mdates.date2num(t0), np.nan]
  51. tnp = np.array([t0, 'NaT'], dtype=dtype)
  52. nptime = mdates.date2num(tnp)
  53. np.testing.assert_array_equal(tmpl, nptime)
  54. @pytest.mark.parametrize('units', ['s', 'ms', 'us', 'ns'])
  55. def test_date2num_NaT_scalar(units):
  56. tmpl = mdates.date2num(np.datetime64('NaT', units))
  57. assert np.isnan(tmpl)
  58. @image_comparison(['date_empty.png'])
  59. def test_date_empty():
  60. # make sure we do the right thing when told to plot dates even
  61. # if no date data has been presented, cf
  62. # http://sourceforge.net/tracker/?func=detail&aid=2850075&group_id=80706&atid=560720
  63. fig = plt.figure()
  64. ax = fig.add_subplot(1, 1, 1)
  65. ax.xaxis_date()
  66. @image_comparison(['date_axhspan.png'])
  67. def test_date_axhspan():
  68. # test ax hspan with date inputs
  69. t0 = datetime.datetime(2009, 1, 20)
  70. tf = datetime.datetime(2009, 1, 21)
  71. fig = plt.figure()
  72. ax = fig.add_subplot(1, 1, 1)
  73. ax.axhspan(t0, tf, facecolor="blue", alpha=0.25)
  74. ax.set_ylim(t0 - datetime.timedelta(days=5),
  75. tf + datetime.timedelta(days=5))
  76. fig.subplots_adjust(left=0.25)
  77. @image_comparison(['date_axvspan.png'])
  78. def test_date_axvspan():
  79. # test ax hspan with date inputs
  80. t0 = datetime.datetime(2000, 1, 20)
  81. tf = datetime.datetime(2010, 1, 21)
  82. fig = plt.figure()
  83. ax = fig.add_subplot(1, 1, 1)
  84. ax.axvspan(t0, tf, facecolor="blue", alpha=0.25)
  85. ax.set_xlim(t0 - datetime.timedelta(days=720),
  86. tf + datetime.timedelta(days=720))
  87. fig.autofmt_xdate()
  88. @image_comparison(['date_axhline.png'])
  89. def test_date_axhline():
  90. # test ax hline with date inputs
  91. t0 = datetime.datetime(2009, 1, 20)
  92. tf = datetime.datetime(2009, 1, 31)
  93. fig = plt.figure()
  94. ax = fig.add_subplot(1, 1, 1)
  95. ax.axhline(t0, color="blue", lw=3)
  96. ax.set_ylim(t0 - datetime.timedelta(days=5),
  97. tf + datetime.timedelta(days=5))
  98. fig.subplots_adjust(left=0.25)
  99. @image_comparison(['date_axvline.png'])
  100. def test_date_axvline():
  101. # test ax hline with date inputs
  102. t0 = datetime.datetime(2000, 1, 20)
  103. tf = datetime.datetime(2000, 1, 21)
  104. fig = plt.figure()
  105. ax = fig.add_subplot(1, 1, 1)
  106. ax.axvline(t0, color="red", lw=3)
  107. ax.set_xlim(t0 - datetime.timedelta(days=5),
  108. tf + datetime.timedelta(days=5))
  109. fig.autofmt_xdate()
  110. def test_too_many_date_ticks(caplog):
  111. # Attempt to test SF 2715172, see
  112. # https://sourceforge.net/tracker/?func=detail&aid=2715172&group_id=80706&atid=560720
  113. # setting equal datetimes triggers and expander call in
  114. # transforms.nonsingular which results in too many ticks in the
  115. # DayLocator. This should emit a log at WARNING level.
  116. caplog.set_level("WARNING")
  117. t0 = datetime.datetime(2000, 1, 20)
  118. tf = datetime.datetime(2000, 1, 20)
  119. fig = plt.figure()
  120. ax = fig.add_subplot(1, 1, 1)
  121. with pytest.warns(UserWarning) as rec:
  122. ax.set_xlim((t0, tf), auto=True)
  123. assert len(rec) == 1
  124. assert \
  125. 'Attempting to set identical left == right' in str(rec[0].message)
  126. ax.plot([], [])
  127. ax.xaxis.set_major_locator(mdates.DayLocator())
  128. v = ax.xaxis.get_major_locator()()
  129. assert len(v) > 1000
  130. # The warning is emitted multiple times because the major locator is also
  131. # called both when placing the minor ticks (for overstriking detection) and
  132. # during tick label positioning.
  133. assert caplog.records and all(
  134. record.name == "matplotlib.ticker" and record.levelname == "WARNING"
  135. for record in caplog.records)
  136. assert len(caplog.records) > 0
  137. def _new_epoch_decorator(thefunc):
  138. @functools.wraps(thefunc)
  139. def wrapper():
  140. mdates._reset_epoch_test_example()
  141. mdates.set_epoch('2000-01-01')
  142. thefunc()
  143. mdates._reset_epoch_test_example()
  144. return wrapper
  145. @image_comparison(['RRuleLocator_bounds.png'])
  146. def test_RRuleLocator():
  147. import matplotlib.testing.jpl_units as units
  148. units.register()
  149. # This will cause the RRuleLocator to go out of bounds when it tries
  150. # to add padding to the limits, so we make sure it caps at the correct
  151. # boundary values.
  152. t0 = datetime.datetime(1000, 1, 1)
  153. tf = datetime.datetime(6000, 1, 1)
  154. fig = plt.figure()
  155. ax = plt.subplot(111)
  156. ax.set_autoscale_on(True)
  157. ax.plot([t0, tf], [0.0, 1.0], marker='o')
  158. rrule = mdates.rrulewrapper(dateutil.rrule.YEARLY, interval=500)
  159. locator = mdates.RRuleLocator(rrule)
  160. ax.xaxis.set_major_locator(locator)
  161. ax.xaxis.set_major_formatter(mdates.AutoDateFormatter(locator))
  162. ax.autoscale_view()
  163. fig.autofmt_xdate()
  164. def test_RRuleLocator_dayrange():
  165. loc = mdates.DayLocator()
  166. x1 = datetime.datetime(year=1, month=1, day=1, tzinfo=mdates.UTC)
  167. y1 = datetime.datetime(year=1, month=1, day=16, tzinfo=mdates.UTC)
  168. loc.tick_values(x1, y1)
  169. # On success, no overflow error shall be thrown
  170. @image_comparison(['DateFormatter_fractionalSeconds.png'])
  171. def test_DateFormatter():
  172. import matplotlib.testing.jpl_units as units
  173. units.register()
  174. # Lets make sure that DateFormatter will allow us to have tick marks
  175. # at intervals of fractional seconds.
  176. t0 = datetime.datetime(2001, 1, 1, 0, 0, 0)
  177. tf = datetime.datetime(2001, 1, 1, 0, 0, 1)
  178. fig = plt.figure()
  179. ax = plt.subplot(111)
  180. ax.set_autoscale_on(True)
  181. ax.plot([t0, tf], [0.0, 1.0], marker='o')
  182. # rrule = mpldates.rrulewrapper( dateutil.rrule.YEARLY, interval=500 )
  183. # locator = mpldates.RRuleLocator( rrule )
  184. # ax.xaxis.set_major_locator( locator )
  185. # ax.xaxis.set_major_formatter( mpldates.AutoDateFormatter(locator) )
  186. ax.autoscale_view()
  187. fig.autofmt_xdate()
  188. def test_locator_set_formatter():
  189. """
  190. Test if setting the locator only will update the AutoDateFormatter to use
  191. the new locator.
  192. """
  193. plt.rcParams["date.autoformatter.minute"] = "%d %H:%M"
  194. t = [datetime.datetime(2018, 9, 30, 8, 0),
  195. datetime.datetime(2018, 9, 30, 8, 59),
  196. datetime.datetime(2018, 9, 30, 10, 30)]
  197. x = [2, 3, 1]
  198. fig, ax = plt.subplots()
  199. ax.plot(t, x)
  200. ax.xaxis.set_major_locator(mdates.MinuteLocator((0, 30)))
  201. fig.canvas.draw()
  202. ticklabels = [tl.get_text() for tl in ax.get_xticklabels()]
  203. expected = ['30 08:00', '30 08:30', '30 09:00',
  204. '30 09:30', '30 10:00', '30 10:30']
  205. assert ticklabels == expected
  206. ax.xaxis.set_major_locator(mticker.NullLocator())
  207. ax.xaxis.set_minor_locator(mdates.MinuteLocator((5, 55)))
  208. decoy_loc = mdates.MinuteLocator((12, 27))
  209. ax.xaxis.set_minor_formatter(mdates.AutoDateFormatter(decoy_loc))
  210. ax.xaxis.set_minor_locator(mdates.MinuteLocator((15, 45)))
  211. fig.canvas.draw()
  212. ticklabels = [tl.get_text() for tl in ax.get_xticklabels(which="minor")]
  213. expected = ['30 08:15', '30 08:45', '30 09:15', '30 09:45', '30 10:15']
  214. assert ticklabels == expected
  215. def test_date_formatter_callable():
  216. class _Locator:
  217. def _get_unit(self): return -11
  218. def callable_formatting_function(dates, _):
  219. return [dt.strftime('%d-%m//%Y') for dt in dates]
  220. formatter = mdates.AutoDateFormatter(_Locator())
  221. formatter.scaled[-10] = callable_formatting_function
  222. assert formatter([datetime.datetime(2014, 12, 25)]) == ['25-12//2014']
  223. def test_drange():
  224. """
  225. This test should check if drange works as expected, and if all the
  226. rounding errors are fixed
  227. """
  228. start = datetime.datetime(2011, 1, 1, tzinfo=mdates.UTC)
  229. end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC)
  230. delta = datetime.timedelta(hours=1)
  231. # We expect 24 values in drange(start, end, delta), because drange returns
  232. # dates from an half open interval [start, end)
  233. assert len(mdates.drange(start, end, delta)) == 24
  234. # if end is a little bit later, we expect the range to contain one element
  235. # more
  236. end = end + datetime.timedelta(microseconds=1)
  237. assert len(mdates.drange(start, end, delta)) == 25
  238. # reset end
  239. end = datetime.datetime(2011, 1, 2, tzinfo=mdates.UTC)
  240. # and tst drange with "complicated" floats:
  241. # 4 hours = 1/6 day, this is an "dangerous" float
  242. delta = datetime.timedelta(hours=4)
  243. daterange = mdates.drange(start, end, delta)
  244. assert len(daterange) == 6
  245. assert mdates.num2date(daterange[-1]) == (end - delta)
  246. @_new_epoch_decorator
  247. def test_auto_date_locator():
  248. def _create_auto_date_locator(date1, date2):
  249. locator = mdates.AutoDateLocator(interval_multiples=False)
  250. locator.create_dummy_axis()
  251. locator.set_view_interval(mdates.date2num(date1),
  252. mdates.date2num(date2))
  253. return locator
  254. d1 = datetime.datetime(1990, 1, 1)
  255. results = ([datetime.timedelta(weeks=52 * 200),
  256. ['1990-01-01 00:00:00+00:00', '2010-01-01 00:00:00+00:00',
  257. '2030-01-01 00:00:00+00:00', '2050-01-01 00:00:00+00:00',
  258. '2070-01-01 00:00:00+00:00', '2090-01-01 00:00:00+00:00',
  259. '2110-01-01 00:00:00+00:00', '2130-01-01 00:00:00+00:00',
  260. '2150-01-01 00:00:00+00:00', '2170-01-01 00:00:00+00:00']
  261. ],
  262. [datetime.timedelta(weeks=52),
  263. ['1990-01-01 00:00:00+00:00', '1990-02-01 00:00:00+00:00',
  264. '1990-03-01 00:00:00+00:00', '1990-04-01 00:00:00+00:00',
  265. '1990-05-01 00:00:00+00:00', '1990-06-01 00:00:00+00:00',
  266. '1990-07-01 00:00:00+00:00', '1990-08-01 00:00:00+00:00',
  267. '1990-09-01 00:00:00+00:00', '1990-10-01 00:00:00+00:00',
  268. '1990-11-01 00:00:00+00:00', '1990-12-01 00:00:00+00:00']
  269. ],
  270. [datetime.timedelta(days=141),
  271. ['1990-01-05 00:00:00+00:00', '1990-01-26 00:00:00+00:00',
  272. '1990-02-16 00:00:00+00:00', '1990-03-09 00:00:00+00:00',
  273. '1990-03-30 00:00:00+00:00', '1990-04-20 00:00:00+00:00',
  274. '1990-05-11 00:00:00+00:00']
  275. ],
  276. [datetime.timedelta(days=40),
  277. ['1990-01-03 00:00:00+00:00', '1990-01-10 00:00:00+00:00',
  278. '1990-01-17 00:00:00+00:00', '1990-01-24 00:00:00+00:00',
  279. '1990-01-31 00:00:00+00:00', '1990-02-07 00:00:00+00:00']
  280. ],
  281. [datetime.timedelta(hours=40),
  282. ['1990-01-01 00:00:00+00:00', '1990-01-01 04:00:00+00:00',
  283. '1990-01-01 08:00:00+00:00', '1990-01-01 12:00:00+00:00',
  284. '1990-01-01 16:00:00+00:00', '1990-01-01 20:00:00+00:00',
  285. '1990-01-02 00:00:00+00:00', '1990-01-02 04:00:00+00:00',
  286. '1990-01-02 08:00:00+00:00', '1990-01-02 12:00:00+00:00',
  287. '1990-01-02 16:00:00+00:00']
  288. ],
  289. [datetime.timedelta(minutes=20),
  290. ['1990-01-01 00:00:00+00:00', '1990-01-01 00:05:00+00:00',
  291. '1990-01-01 00:10:00+00:00', '1990-01-01 00:15:00+00:00',
  292. '1990-01-01 00:20:00+00:00']
  293. ],
  294. [datetime.timedelta(seconds=40),
  295. ['1990-01-01 00:00:00+00:00', '1990-01-01 00:00:05+00:00',
  296. '1990-01-01 00:00:10+00:00', '1990-01-01 00:00:15+00:00',
  297. '1990-01-01 00:00:20+00:00', '1990-01-01 00:00:25+00:00',
  298. '1990-01-01 00:00:30+00:00', '1990-01-01 00:00:35+00:00',
  299. '1990-01-01 00:00:40+00:00']
  300. ],
  301. [datetime.timedelta(microseconds=1500),
  302. ['1989-12-31 23:59:59.999500+00:00',
  303. '1990-01-01 00:00:00+00:00',
  304. '1990-01-01 00:00:00.000500+00:00',
  305. '1990-01-01 00:00:00.001000+00:00',
  306. '1990-01-01 00:00:00.001500+00:00',
  307. '1990-01-01 00:00:00.002000+00:00']
  308. ],
  309. )
  310. for t_delta, expected in results:
  311. d2 = d1 + t_delta
  312. locator = _create_auto_date_locator(d1, d2)
  313. assert list(map(str, mdates.num2date(locator()))) == expected
  314. @_new_epoch_decorator
  315. def test_auto_date_locator_intmult():
  316. def _create_auto_date_locator(date1, date2):
  317. locator = mdates.AutoDateLocator(interval_multiples=True)
  318. locator.create_dummy_axis()
  319. locator.set_view_interval(mdates.date2num(date1),
  320. mdates.date2num(date2))
  321. return locator
  322. results = ([datetime.timedelta(weeks=52 * 200),
  323. ['1980-01-01 00:00:00+00:00', '2000-01-01 00:00:00+00:00',
  324. '2020-01-01 00:00:00+00:00', '2040-01-01 00:00:00+00:00',
  325. '2060-01-01 00:00:00+00:00', '2080-01-01 00:00:00+00:00',
  326. '2100-01-01 00:00:00+00:00', '2120-01-01 00:00:00+00:00',
  327. '2140-01-01 00:00:00+00:00', '2160-01-01 00:00:00+00:00',
  328. '2180-01-01 00:00:00+00:00', '2200-01-01 00:00:00+00:00']
  329. ],
  330. [datetime.timedelta(weeks=52),
  331. ['1997-01-01 00:00:00+00:00', '1997-02-01 00:00:00+00:00',
  332. '1997-03-01 00:00:00+00:00', '1997-04-01 00:00:00+00:00',
  333. '1997-05-01 00:00:00+00:00', '1997-06-01 00:00:00+00:00',
  334. '1997-07-01 00:00:00+00:00', '1997-08-01 00:00:00+00:00',
  335. '1997-09-01 00:00:00+00:00', '1997-10-01 00:00:00+00:00',
  336. '1997-11-01 00:00:00+00:00', '1997-12-01 00:00:00+00:00']
  337. ],
  338. [datetime.timedelta(days=141),
  339. ['1997-01-01 00:00:00+00:00', '1997-01-22 00:00:00+00:00',
  340. '1997-02-01 00:00:00+00:00', '1997-02-22 00:00:00+00:00',
  341. '1997-03-01 00:00:00+00:00', '1997-03-22 00:00:00+00:00',
  342. '1997-04-01 00:00:00+00:00', '1997-04-22 00:00:00+00:00',
  343. '1997-05-01 00:00:00+00:00', '1997-05-22 00:00:00+00:00']
  344. ],
  345. [datetime.timedelta(days=40),
  346. ['1997-01-01 00:00:00+00:00', '1997-01-05 00:00:00+00:00',
  347. '1997-01-09 00:00:00+00:00', '1997-01-13 00:00:00+00:00',
  348. '1997-01-17 00:00:00+00:00', '1997-01-21 00:00:00+00:00',
  349. '1997-01-25 00:00:00+00:00', '1997-01-29 00:00:00+00:00',
  350. '1997-02-01 00:00:00+00:00', '1997-02-05 00:00:00+00:00',
  351. '1997-02-09 00:00:00+00:00']
  352. ],
  353. [datetime.timedelta(hours=40),
  354. ['1997-01-01 00:00:00+00:00', '1997-01-01 04:00:00+00:00',
  355. '1997-01-01 08:00:00+00:00', '1997-01-01 12:00:00+00:00',
  356. '1997-01-01 16:00:00+00:00', '1997-01-01 20:00:00+00:00',
  357. '1997-01-02 00:00:00+00:00', '1997-01-02 04:00:00+00:00',
  358. '1997-01-02 08:00:00+00:00', '1997-01-02 12:00:00+00:00',
  359. '1997-01-02 16:00:00+00:00']
  360. ],
  361. [datetime.timedelta(minutes=20),
  362. ['1997-01-01 00:00:00+00:00', '1997-01-01 00:05:00+00:00',
  363. '1997-01-01 00:10:00+00:00', '1997-01-01 00:15:00+00:00',
  364. '1997-01-01 00:20:00+00:00']
  365. ],
  366. [datetime.timedelta(seconds=40),
  367. ['1997-01-01 00:00:00+00:00', '1997-01-01 00:00:05+00:00',
  368. '1997-01-01 00:00:10+00:00', '1997-01-01 00:00:15+00:00',
  369. '1997-01-01 00:00:20+00:00', '1997-01-01 00:00:25+00:00',
  370. '1997-01-01 00:00:30+00:00', '1997-01-01 00:00:35+00:00',
  371. '1997-01-01 00:00:40+00:00']
  372. ],
  373. [datetime.timedelta(microseconds=1500),
  374. ['1996-12-31 23:59:59.999500+00:00',
  375. '1997-01-01 00:00:00+00:00',
  376. '1997-01-01 00:00:00.000500+00:00',
  377. '1997-01-01 00:00:00.001000+00:00',
  378. '1997-01-01 00:00:00.001500+00:00',
  379. '1997-01-01 00:00:00.002000+00:00']
  380. ],
  381. )
  382. d1 = datetime.datetime(1997, 1, 1)
  383. for t_delta, expected in results:
  384. d2 = d1 + t_delta
  385. locator = _create_auto_date_locator(d1, d2)
  386. assert list(map(str, mdates.num2date(locator()))) == expected
  387. def test_concise_formatter():
  388. def _create_auto_date_locator(date1, date2):
  389. fig, ax = plt.subplots()
  390. locator = mdates.AutoDateLocator(interval_multiples=True)
  391. formatter = mdates.ConciseDateFormatter(locator)
  392. ax.yaxis.set_major_locator(locator)
  393. ax.yaxis.set_major_formatter(formatter)
  394. ax.set_ylim(date1, date2)
  395. fig.canvas.draw()
  396. sts = [st.get_text() for st in ax.get_yticklabels()]
  397. return sts
  398. d1 = datetime.datetime(1997, 1, 1)
  399. results = ([datetime.timedelta(weeks=52 * 200),
  400. [str(t) for t in range(1980, 2201, 20)]
  401. ],
  402. [datetime.timedelta(weeks=52),
  403. ['1997', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug',
  404. 'Sep', 'Oct', 'Nov', 'Dec']
  405. ],
  406. [datetime.timedelta(days=141),
  407. ['Jan', '22', 'Feb', '22', 'Mar', '22', 'Apr', '22',
  408. 'May', '22']
  409. ],
  410. [datetime.timedelta(days=40),
  411. ['Jan', '05', '09', '13', '17', '21', '25', '29', 'Feb',
  412. '05', '09']
  413. ],
  414. [datetime.timedelta(hours=40),
  415. ['Jan-01', '04:00', '08:00', '12:00', '16:00', '20:00',
  416. 'Jan-02', '04:00', '08:00', '12:00', '16:00']
  417. ],
  418. [datetime.timedelta(minutes=20),
  419. ['00:00', '00:05', '00:10', '00:15', '00:20']
  420. ],
  421. [datetime.timedelta(seconds=40),
  422. ['00:00', '05', '10', '15', '20', '25', '30', '35', '40']
  423. ],
  424. [datetime.timedelta(seconds=2),
  425. ['59.5', '00:00', '00.5', '01.0', '01.5', '02.0', '02.5']
  426. ],
  427. )
  428. for t_delta, expected in results:
  429. d2 = d1 + t_delta
  430. strings = _create_auto_date_locator(d1, d2)
  431. assert strings == expected
  432. def test_concise_formatter_formats():
  433. formats = ['%Y', '%m/%Y', 'day: %d',
  434. '%H hr %M min', '%H hr %M min', '%S.%f sec']
  435. def _create_auto_date_locator(date1, date2):
  436. fig, ax = plt.subplots()
  437. locator = mdates.AutoDateLocator(interval_multiples=True)
  438. formatter = mdates.ConciseDateFormatter(locator, formats=formats)
  439. ax.yaxis.set_major_locator(locator)
  440. ax.yaxis.set_major_formatter(formatter)
  441. ax.set_ylim(date1, date2)
  442. fig.canvas.draw()
  443. sts = [st.get_text() for st in ax.get_yticklabels()]
  444. return sts
  445. d1 = datetime.datetime(1997, 1, 1)
  446. results = (
  447. [datetime.timedelta(weeks=52 * 200), [str(t) for t in range(1980,
  448. 2201, 20)]],
  449. [datetime.timedelta(weeks=52), [
  450. '1997', '02/1997', '03/1997', '04/1997', '05/1997', '06/1997',
  451. '07/1997', '08/1997', '09/1997', '10/1997', '11/1997', '12/1997',
  452. ]],
  453. [datetime.timedelta(days=141), [
  454. '01/1997', 'day: 22', '02/1997', 'day: 22', '03/1997', 'day: 22',
  455. '04/1997', 'day: 22', '05/1997', 'day: 22',
  456. ]],
  457. [datetime.timedelta(days=40), [
  458. '01/1997', 'day: 05', 'day: 09', 'day: 13', 'day: 17', 'day: 21',
  459. 'day: 25', 'day: 29', '02/1997', 'day: 05', 'day: 09',
  460. ]],
  461. [datetime.timedelta(hours=40), [
  462. 'day: 01', '04 hr 00 min', '08 hr 00 min', '12 hr 00 min',
  463. '16 hr 00 min', '20 hr 00 min', 'day: 02', '04 hr 00 min',
  464. '08 hr 00 min', '12 hr 00 min', '16 hr 00 min',
  465. ]],
  466. [datetime.timedelta(minutes=20), ['00 hr 00 min', '00 hr 05 min',
  467. '00 hr 10 min', '00 hr 15 min', '00 hr 20 min']],
  468. [datetime.timedelta(seconds=40), [
  469. '00 hr 00 min', '05.000000 sec', '10.000000 sec',
  470. '15.000000 sec', '20.000000 sec', '25.000000 sec',
  471. '30.000000 sec', '35.000000 sec', '40.000000 sec',
  472. ]],
  473. [datetime.timedelta(seconds=2), [
  474. '59.500000 sec', '00 hr 00 min', '00.500000 sec', '01.000000 sec',
  475. '01.500000 sec', '02.000000 sec', '02.500000 sec',
  476. ]],
  477. )
  478. for t_delta, expected in results:
  479. d2 = d1 + t_delta
  480. strings = _create_auto_date_locator(d1, d2)
  481. assert strings == expected
  482. def test_concise_formatter_zformats():
  483. zero_formats = ['', "'%y", '%B', '%m-%d', '%S', '%S.%f']
  484. def _create_auto_date_locator(date1, date2):
  485. fig, ax = plt.subplots()
  486. locator = mdates.AutoDateLocator(interval_multiples=True)
  487. formatter = mdates.ConciseDateFormatter(
  488. locator, zero_formats=zero_formats)
  489. ax.yaxis.set_major_locator(locator)
  490. ax.yaxis.set_major_formatter(formatter)
  491. ax.set_ylim(date1, date2)
  492. fig.canvas.draw()
  493. sts = [st.get_text() for st in ax.get_yticklabels()]
  494. return sts
  495. d1 = datetime.datetime(1997, 1, 1)
  496. results = ([datetime.timedelta(weeks=52 * 200),
  497. [str(t) for t in range(1980, 2201, 20)]
  498. ],
  499. [datetime.timedelta(weeks=52),
  500. ["'97", 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  501. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  502. ],
  503. [datetime.timedelta(days=141),
  504. ['January', '22', 'February', '22', 'March',
  505. '22', 'April', '22', 'May', '22']
  506. ],
  507. [datetime.timedelta(days=40),
  508. ['January', '05', '09', '13', '17', '21',
  509. '25', '29', 'February', '05', '09']
  510. ],
  511. [datetime.timedelta(hours=40),
  512. ['01-01', '04:00', '08:00', '12:00', '16:00', '20:00',
  513. '01-02', '04:00', '08:00', '12:00', '16:00']
  514. ],
  515. [datetime.timedelta(minutes=20),
  516. ['00', '00:05', '00:10', '00:15', '00:20']
  517. ],
  518. [datetime.timedelta(seconds=40),
  519. ['00', '05', '10', '15', '20', '25', '30', '35', '40']
  520. ],
  521. [datetime.timedelta(seconds=2),
  522. ['59.5', '00.0', '00.5', '01.0', '01.5', '02.0', '02.5']
  523. ],
  524. )
  525. for t_delta, expected in results:
  526. d2 = d1 + t_delta
  527. strings = _create_auto_date_locator(d1, d2)
  528. assert strings == expected
  529. def test_concise_formatter_tz():
  530. def _create_auto_date_locator(date1, date2, tz):
  531. fig, ax = plt.subplots()
  532. locator = mdates.AutoDateLocator(interval_multiples=True)
  533. formatter = mdates.ConciseDateFormatter(locator, tz=tz)
  534. ax.yaxis.set_major_locator(locator)
  535. ax.yaxis.set_major_formatter(formatter)
  536. ax.set_ylim(date1, date2)
  537. fig.canvas.draw()
  538. sts = [st.get_text() for st in ax.get_yticklabels()]
  539. return sts, ax.yaxis.get_offset_text().get_text()
  540. d1 = datetime.datetime(1997, 1, 1).replace(tzinfo=datetime.timezone.utc)
  541. results = ([datetime.timedelta(hours=40),
  542. ['03:00', '07:00', '11:00', '15:00', '19:00', '23:00',
  543. '03:00', '07:00', '11:00', '15:00', '19:00'],
  544. "1997-Jan-02"
  545. ],
  546. [datetime.timedelta(minutes=20),
  547. ['03:00', '03:05', '03:10', '03:15', '03:20'],
  548. "1997-Jan-01"
  549. ],
  550. [datetime.timedelta(seconds=40),
  551. ['03:00', '05', '10', '15', '20', '25', '30', '35', '40'],
  552. "1997-Jan-01 03:00"
  553. ],
  554. [datetime.timedelta(seconds=2),
  555. ['59.5', '03:00', '00.5', '01.0', '01.5', '02.0', '02.5'],
  556. "1997-Jan-01 03:00"
  557. ],
  558. )
  559. new_tz = datetime.timezone(datetime.timedelta(hours=3))
  560. for t_delta, expected_strings, expected_offset in results:
  561. d2 = d1 + t_delta
  562. strings, offset = _create_auto_date_locator(d1, d2, new_tz)
  563. assert strings == expected_strings
  564. assert offset == expected_offset
  565. def test_auto_date_locator_intmult_tz():
  566. def _create_auto_date_locator(date1, date2, tz):
  567. locator = mdates.AutoDateLocator(interval_multiples=True, tz=tz)
  568. locator.create_dummy_axis()
  569. locator.set_view_interval(mdates.date2num(date1),
  570. mdates.date2num(date2))
  571. return locator
  572. results = ([datetime.timedelta(weeks=52*200),
  573. ['1980-01-01 00:00:00-08:00', '2000-01-01 00:00:00-08:00',
  574. '2020-01-01 00:00:00-08:00', '2040-01-01 00:00:00-08:00',
  575. '2060-01-01 00:00:00-08:00', '2080-01-01 00:00:00-08:00',
  576. '2100-01-01 00:00:00-08:00', '2120-01-01 00:00:00-08:00',
  577. '2140-01-01 00:00:00-08:00', '2160-01-01 00:00:00-08:00',
  578. '2180-01-01 00:00:00-08:00', '2200-01-01 00:00:00-08:00']
  579. ],
  580. [datetime.timedelta(weeks=52),
  581. ['1997-01-01 00:00:00-08:00', '1997-02-01 00:00:00-08:00',
  582. '1997-03-01 00:00:00-08:00', '1997-04-01 00:00:00-08:00',
  583. '1997-05-01 00:00:00-07:00', '1997-06-01 00:00:00-07:00',
  584. '1997-07-01 00:00:00-07:00', '1997-08-01 00:00:00-07:00',
  585. '1997-09-01 00:00:00-07:00', '1997-10-01 00:00:00-07:00',
  586. '1997-11-01 00:00:00-08:00', '1997-12-01 00:00:00-08:00']
  587. ],
  588. [datetime.timedelta(days=141),
  589. ['1997-01-01 00:00:00-08:00', '1997-01-22 00:00:00-08:00',
  590. '1997-02-01 00:00:00-08:00', '1997-02-22 00:00:00-08:00',
  591. '1997-03-01 00:00:00-08:00', '1997-03-22 00:00:00-08:00',
  592. '1997-04-01 00:00:00-08:00', '1997-04-22 00:00:00-07:00',
  593. '1997-05-01 00:00:00-07:00', '1997-05-22 00:00:00-07:00']
  594. ],
  595. [datetime.timedelta(days=40),
  596. ['1997-01-01 00:00:00-08:00', '1997-01-05 00:00:00-08:00',
  597. '1997-01-09 00:00:00-08:00', '1997-01-13 00:00:00-08:00',
  598. '1997-01-17 00:00:00-08:00', '1997-01-21 00:00:00-08:00',
  599. '1997-01-25 00:00:00-08:00', '1997-01-29 00:00:00-08:00',
  600. '1997-02-01 00:00:00-08:00', '1997-02-05 00:00:00-08:00',
  601. '1997-02-09 00:00:00-08:00']
  602. ],
  603. [datetime.timedelta(hours=40),
  604. ['1997-01-01 00:00:00-08:00', '1997-01-01 04:00:00-08:00',
  605. '1997-01-01 08:00:00-08:00', '1997-01-01 12:00:00-08:00',
  606. '1997-01-01 16:00:00-08:00', '1997-01-01 20:00:00-08:00',
  607. '1997-01-02 00:00:00-08:00', '1997-01-02 04:00:00-08:00',
  608. '1997-01-02 08:00:00-08:00', '1997-01-02 12:00:00-08:00',
  609. '1997-01-02 16:00:00-08:00']
  610. ],
  611. [datetime.timedelta(minutes=20),
  612. ['1997-01-01 00:00:00-08:00', '1997-01-01 00:05:00-08:00',
  613. '1997-01-01 00:10:00-08:00', '1997-01-01 00:15:00-08:00',
  614. '1997-01-01 00:20:00-08:00']
  615. ],
  616. [datetime.timedelta(seconds=40),
  617. ['1997-01-01 00:00:00-08:00', '1997-01-01 00:00:05-08:00',
  618. '1997-01-01 00:00:10-08:00', '1997-01-01 00:00:15-08:00',
  619. '1997-01-01 00:00:20-08:00', '1997-01-01 00:00:25-08:00',
  620. '1997-01-01 00:00:30-08:00', '1997-01-01 00:00:35-08:00',
  621. '1997-01-01 00:00:40-08:00']
  622. ]
  623. )
  624. tz = dateutil.tz.gettz('Canada/Pacific')
  625. d1 = datetime.datetime(1997, 1, 1, tzinfo=tz)
  626. for t_delta, expected in results:
  627. with rc_context({'_internal.classic_mode': False}):
  628. d2 = d1 + t_delta
  629. locator = _create_auto_date_locator(d1, d2, tz)
  630. st = list(map(str, mdates.num2date(locator(), tz=tz)))
  631. assert st == expected
  632. @image_comparison(['date_inverted_limit.png'])
  633. def test_date_inverted_limit():
  634. # test ax hline with date inputs
  635. t0 = datetime.datetime(2009, 1, 20)
  636. tf = datetime.datetime(2009, 1, 31)
  637. fig = plt.figure()
  638. ax = fig.add_subplot(1, 1, 1)
  639. ax.axhline(t0, color="blue", lw=3)
  640. ax.set_ylim(t0 - datetime.timedelta(days=5),
  641. tf + datetime.timedelta(days=5))
  642. ax.invert_yaxis()
  643. fig.subplots_adjust(left=0.25)
  644. def _test_date2num_dst(date_range, tz_convert):
  645. # Timezones
  646. BRUSSELS = dateutil.tz.gettz('Europe/Brussels')
  647. UTC = mdates.UTC
  648. # Create a list of timezone-aware datetime objects in UTC
  649. # Interval is 0b0.0000011 days, to prevent float rounding issues
  650. dtstart = datetime.datetime(2014, 3, 30, 0, 0, tzinfo=UTC)
  651. interval = datetime.timedelta(minutes=33, seconds=45)
  652. interval_days = 0.0234375 # 2025 / 86400 seconds
  653. N = 8
  654. dt_utc = date_range(start=dtstart, freq=interval, periods=N)
  655. dt_bxl = tz_convert(dt_utc, BRUSSELS)
  656. t0 = 735322.0 + mdates.date2num(np.datetime64('0000-12-31'))
  657. expected_ordinalf = [t0 + (i * interval_days) for i in range(N)]
  658. actual_ordinalf = list(mdates.date2num(dt_bxl))
  659. assert actual_ordinalf == expected_ordinalf
  660. def test_date2num_dst():
  661. # Test for github issue #3896, but in date2num around DST transitions
  662. # with a timezone-aware pandas date_range object.
  663. class dt_tzaware(datetime.datetime):
  664. """
  665. This bug specifically occurs because of the normalization behavior of
  666. pandas Timestamp objects, so in order to replicate it, we need a
  667. datetime-like object that applies timezone normalization after
  668. subtraction.
  669. """
  670. def __sub__(self, other):
  671. r = super().__sub__(other)
  672. tzinfo = getattr(r, 'tzinfo', None)
  673. if tzinfo is not None:
  674. localizer = getattr(tzinfo, 'normalize', None)
  675. if localizer is not None:
  676. r = tzinfo.normalize(r)
  677. if isinstance(r, datetime.datetime):
  678. r = self.mk_tzaware(r)
  679. return r
  680. def __add__(self, other):
  681. return self.mk_tzaware(super().__add__(other))
  682. def astimezone(self, tzinfo):
  683. dt = super().astimezone(tzinfo)
  684. return self.mk_tzaware(dt)
  685. @classmethod
  686. def mk_tzaware(cls, datetime_obj):
  687. kwargs = {}
  688. attrs = ('year',
  689. 'month',
  690. 'day',
  691. 'hour',
  692. 'minute',
  693. 'second',
  694. 'microsecond',
  695. 'tzinfo')
  696. for attr in attrs:
  697. val = getattr(datetime_obj, attr, None)
  698. if val is not None:
  699. kwargs[attr] = val
  700. return cls(**kwargs)
  701. # Define a date_range function similar to pandas.date_range
  702. def date_range(start, freq, periods):
  703. dtstart = dt_tzaware.mk_tzaware(start)
  704. return [dtstart + (i * freq) for i in range(periods)]
  705. # Define a tz_convert function that converts a list to a new time zone.
  706. def tz_convert(dt_list, tzinfo):
  707. return [d.astimezone(tzinfo) for d in dt_list]
  708. _test_date2num_dst(date_range, tz_convert)
  709. def test_date2num_dst_pandas(pd):
  710. # Test for github issue #3896, but in date2num around DST transitions
  711. # with a timezone-aware pandas date_range object.
  712. def tz_convert(*args):
  713. return pd.DatetimeIndex.tz_convert(*args).astype(object)
  714. _test_date2num_dst(pd.date_range, tz_convert)
  715. def _test_rrulewrapper(attach_tz, get_tz):
  716. SYD = get_tz('Australia/Sydney')
  717. dtstart = attach_tz(datetime.datetime(2017, 4, 1, 0), SYD)
  718. dtend = attach_tz(datetime.datetime(2017, 4, 4, 0), SYD)
  719. rule = mdates.rrulewrapper(freq=dateutil.rrule.DAILY, dtstart=dtstart)
  720. act = rule.between(dtstart, dtend)
  721. exp = [datetime.datetime(2017, 4, 1, 13, tzinfo=dateutil.tz.tzutc()),
  722. datetime.datetime(2017, 4, 2, 14, tzinfo=dateutil.tz.tzutc())]
  723. assert act == exp
  724. def test_rrulewrapper():
  725. def attach_tz(dt, zi):
  726. return dt.replace(tzinfo=zi)
  727. _test_rrulewrapper(attach_tz, dateutil.tz.gettz)
  728. @pytest.mark.pytz
  729. def test_rrulewrapper_pytz():
  730. # Test to make sure pytz zones are supported in rrules
  731. pytz = pytest.importorskip("pytz")
  732. def attach_tz(dt, zi):
  733. return zi.localize(dt)
  734. _test_rrulewrapper(attach_tz, pytz.timezone)
  735. @pytest.mark.pytz
  736. def test_yearlocator_pytz():
  737. pytz = pytest.importorskip("pytz")
  738. tz = pytz.timezone('America/New_York')
  739. x = [tz.localize(datetime.datetime(2010, 1, 1))
  740. + datetime.timedelta(i) for i in range(2000)]
  741. locator = mdates.AutoDateLocator(interval_multiples=True, tz=tz)
  742. locator.create_dummy_axis()
  743. locator.set_view_interval(mdates.date2num(x[0])-1.0,
  744. mdates.date2num(x[-1])+1.0)
  745. t = np.array([733408.208333, 733773.208333, 734138.208333,
  746. 734503.208333, 734869.208333, 735234.208333, 735599.208333])
  747. # convert to new epoch from old...
  748. t = t + mdates.date2num(np.datetime64('0000-12-31'))
  749. np.testing.assert_allclose(t, locator())
  750. expected = ['2009-01-01 00:00:00-05:00',
  751. '2010-01-01 00:00:00-05:00', '2011-01-01 00:00:00-05:00',
  752. '2012-01-01 00:00:00-05:00', '2013-01-01 00:00:00-05:00',
  753. '2014-01-01 00:00:00-05:00', '2015-01-01 00:00:00-05:00']
  754. st = list(map(str, mdates.num2date(locator(), tz=tz)))
  755. assert st == expected
  756. def test_DayLocator():
  757. with pytest.raises(ValueError):
  758. mdates.DayLocator(interval=-1)
  759. with pytest.raises(ValueError):
  760. mdates.DayLocator(interval=-1.5)
  761. with pytest.raises(ValueError):
  762. mdates.DayLocator(interval=0)
  763. with pytest.raises(ValueError):
  764. mdates.DayLocator(interval=1.3)
  765. mdates.DayLocator(interval=1.0)
  766. def test_tz_utc():
  767. dt = datetime.datetime(1970, 1, 1, tzinfo=mdates.UTC)
  768. dt.tzname()
  769. @pytest.mark.parametrize("x, tdelta",
  770. [(1, datetime.timedelta(days=1)),
  771. ([1, 1.5], [datetime.timedelta(days=1),
  772. datetime.timedelta(days=1.5)])])
  773. def test_num2timedelta(x, tdelta):
  774. dt = mdates.num2timedelta(x)
  775. assert dt == tdelta
  776. def test_datetime64_in_list():
  777. dt = [np.datetime64('2000-01-01'), np.datetime64('2001-01-01')]
  778. dn = mdates.date2num(dt)
  779. # convert fixed values from old to new epoch
  780. t = (np.array([730120., 730486.]) +
  781. mdates.date2num(np.datetime64('0000-12-31')))
  782. np.testing.assert_equal(dn, t)
  783. def test_change_epoch():
  784. date = np.datetime64('2000-01-01')
  785. with pytest.raises(RuntimeError):
  786. # this should fail here because there is a sentinel on the epoch
  787. # if the epoch has been used then it cannot be set.
  788. mdates.set_epoch('0000-01-01')
  789. # use private method to clear the epoch and allow it to be set...
  790. mdates._reset_epoch_test_example()
  791. mdates.set_epoch('1970-01-01')
  792. dt = (date - np.datetime64('1970-01-01')).astype('datetime64[D]')
  793. dt = dt.astype('int')
  794. np.testing.assert_equal(mdates.date2num(date), float(dt))
  795. mdates._reset_epoch_test_example()
  796. mdates.set_epoch('0000-12-31')
  797. np.testing.assert_equal(mdates.date2num(date), 730120.0)
  798. mdates._reset_epoch_test_example()
  799. mdates.set_epoch('1970-01-01T01:00:00')
  800. np.testing.assert_allclose(mdates.date2num(date), dt - 1./24.)
  801. mdates._reset_epoch_test_example()
  802. mdates.set_epoch('1970-01-01T00:00:00')
  803. np.testing.assert_allclose(
  804. mdates.date2num(np.datetime64('1970-01-01T12:00:00')),
  805. 0.5)
  806. def test_epoch2num():
  807. mdates._reset_epoch_test_example()
  808. mdates.set_epoch('0000-12-31')
  809. assert mdates.epoch2num(86400) == 719164.0
  810. assert mdates.num2epoch(719165.0) == 86400 * 2
  811. # set back to the default
  812. mdates._reset_epoch_test_example()
  813. mdates.set_epoch('1970-01-01T00:00:00')
  814. assert mdates.epoch2num(86400) == 1.0
  815. assert mdates.num2epoch(2.0) == 86400 * 2
  816. def test_julian2num():
  817. mdates._reset_epoch_test_example()
  818. mdates.set_epoch('0000-12-31')
  819. # 2440587.5 is julian date for 1970-01-01T00:00:00
  820. # https://en.wikipedia.org/wiki/Julian_day
  821. assert mdates.julian2num(2440588.5) == 719164.0
  822. assert mdates.num2julian(719165.0) == 2440589.5
  823. # set back to the default
  824. mdates._reset_epoch_test_example()
  825. mdates.set_epoch('1970-01-01T00:00:00')
  826. assert mdates.julian2num(2440588.5) == 1.0
  827. assert mdates.num2julian(2.0) == 2440589.5