1

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.

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

2 Comments

I used this along with xticks() and xticklabels(), the issue is, when a lot of values need to be plotted (which is my case), the x axis gets overcrowded. If I don't specify the xticks, matplotlib automatically displays only a few dates, and keeps the plot clean.
The best advice that I can give for this type of situation since I do not use matplotlib is to read the documentation on the ticker format api for matplotlib: matplotlib.org/api/ticker_api.html
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.