Matplotlib.dates.datestr2num() in Python

Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack.

matplotlib.dates.datestr2num()

The matplotlib.dates.datestr2num() function is used to convert a date string to a datenum by the uses of dateutil.parser.parser().

Syntax: matplotlib.dates.datestr2num(d, default=None)

Parameters:

  1. d: It is a string or a sequence of strings representing the dates.
  2. default: This is an optional parameter that is a datetime instance. This is used when fields are not present in d, as a default.

Example 1:



filter_none

edit
close

play_arrow

link
brightness_4
code

from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import (
    DateFormatter, AutoDateLocator, AutoDateFormatter, datestr2num
)
  
  
days = [
    '30/01/2019',
    '31/01/2019'
    '01/02/2019',
    '02/02/2019'
    '03/02/2019'
    '04/02/2019'
]
data1 = [2, 5, 13, 6, 11, 7]
data2 = [6, 3, 10, 3, 6, 5]
  
z = datestr2num([
    datetime.strptime(day, '%d/%m/%Y').strftime('%m/%d/%Y')
    for day in days
])
  
r = 0.25
  
figure = plt.figure(figsize =(8, 4))
axes = figure.add_subplot(111)
  
axes.bar(z - r, data1, width = 2 * r,
         color ='g', align ='center',
         tick_label = day)
  
axes.bar(z + r, data2, width = 2 * r,
         color ='y', align ='center'
         tick_label = day)
  
axes.xaxis_date()
axes.xaxis.set_major_locator(
    AutoDateLocator(minticks = 3, interval_multiples = False))
  
axes.xaxis.set_major_formatter(DateFormatter("%d/%m/%y"))
  
plt.show()

chevron_right


Output:

Example 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.dates
  
  
dates =  ['1920-05-06'
          '1920-05-07'
          '1947-05-08'
          '1920-05-09']
  
converted_dates = matplotlib.dates.datestr2num(dates)
  
x_axis = (converted_dates)
y_axis = range(0, 4)
  
plt.plot_date( x_axis, y_axis, '-' )
  
plt.show()

chevron_right


Output:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.