简体   繁体   中英

Formatting dates python matplotlib

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM