Reputation: 11
I would like to format dates in a dates vs value plot
import datetime as datetime
from matplotlib import pyplot as pl
values = [3, 2, 5]
dates = [datetime.datetime(2014, 3, 30, 10, 56, 11, 889521),datetime.datetime(2014, 4, 1, 6, 16, 11, 889521),datetime.datetime(2014, 4, 2, 12, 16, 11, 889521)]
fig=pl.figure()
graph = fig.add_subplot(111)
graph.plot(dates,values,'k-')
pl.gcf().autofmt_xdate()
pl.show()
gives the following :
The dates are formatted '%H:%M:%S'
.
How could I easily format it to '%d/%m/%Y - %H:%M:%S'
?
I have read numerous answers using num2dates
and so on, but can't find a more direct way.
Upvotes: 1
Views: 329
Reputation: 3777
You could play with the value of nbins in MaxNLocator:
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
fig=pl.figure()
graph = fig.add_subplot(111)
graph.plot(dates,values,'k-')
graph.xaxis.set_major_formatter(mdates.DateFormatter('%d/%m/%Y - %H:%M:%S'))
graph.xaxis.set_major_locator(mticker.MaxNLocator(nbins=5))
pl.show()
Upvotes: 0
Reputation: 24089
You can use strftime() on a datetime
object.
>>> from datetime import datetime
>>> print datetime(2014,2,3,4,5,6).strftime("%d/%m/%y - %H:%M:%S")
Output:
03/02/14 - 04:05:06
Upvotes: 1