2

I have np array or ints, each represent time since epoch (like 1513003977) I would like to plot it as dates, and found out you can do it in x the dates are in datetime.datetime format for can i convert the whole array into datetime?

It is possible to call plt.plot(dates,values) with dates being a list of datetime.datetime objects. The plot will include xticks in a format like '%Y-%m-%d' and as you zoom in, automatically change to one that shows hours, minutes, seconds.

Pavel
  • 7,436
  • 2
  • 29
  • 42
JohnnyF
  • 1,053
  • 4
  • 16
  • 31

1 Answers1

2

Assuming you have a numpy array of timestamps dates, you can do the following

ticks = dates.astype('datetime64[s]').tolist()
plt.plot(ticks, values)

That does two things: first it reinterprets the integer timestamps as numpy's datetime format (the [s] specifies that the units are seconds).

Then, array.tolist(), when called on a datetime64 array, returns a list of datetime.datetime objects, which matplotlib can then use for plotting as you desire.

lxop
  • 7,596
  • 3
  • 27
  • 42