2

I have a datetime array that includes milliseconds. I plot the time only using:

formatterTime = '%H:%M:%S.%f'
ax0.xaxis.set_major_formatter(formatterTime)

However, the datetime array has 6 digits for milliseconds which is plotted as '11:45:05.100000', and I only want 1 millisecond digit, such as '11:45:05.1'.

I've tried suggestions such as

.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

but this only seems to work when printing the datetime to a string.

Is there a way of displaying only the first millisecond digit on the plot, without amending the original date array?

freja
  • 47
  • 1
  • 6
  • 2
    Does this answer your question? [datetime: Round/trim number of digits in microseconds](https://stackoverflow.com/questions/11040177/datetime-round-trim-number-of-digits-in-microseconds) – Ayush Jun 25 '20 at 12:26
  • I don't think so because I can't apply .strftime() to a datetime object, just to a string. – freja Jun 25 '20 at 12:34

1 Answers1

3

You can use FuncFormatter to set your own format. See this example (with some fake data):

from matplotlib.ticker import FuncFormatter
from matplotlib.dates import num2date

x = pd.date_range("2020-01-01", periods = 10, freq = "131ms")
y = range(10)

fig, ax = plt.subplots()

def foo(a, b):
    t = num2date(a)
    ms = str(t.microsecond)[:1]
    res = f"{t.hour:02}:{t.minute:02}:{t.second:02}.{ms}"
    return res

ax.xaxis.set_major_formatter(FuncFormatter(foo))

ax.plot(x, y)

The result is:

enter image description here

Roy2012
  • 11,755
  • 2
  • 22
  • 35