How to calculate date/time in human readable form from epoch format as x-axis-ticks on matplotlib graphs?

Viewed 28

I have panda data frames of time series data. The time is given in epoch format. That is very useful for handling and plotting for the computer, but awkward to read as axis ticks.

Picture with epoch as x-axis ticks

How can I translate the epoch format into human-readable format (like "20.05.2022 14:45") when plotting the graph in matplotlib? Note that I would prefer to keep the epoch format for further handling of the data, and only when plotting use human readable form.

For reference, this reflects the relevant data structure and control flow of my code.

import pandas as pd
import matplotlib.pyplot as plt


mydict = [{'time': 1651816500, 'b': 2},
          {'time': 1651816800, 'b': 200},
          {'time': 1651817100, 'b': 2000}]

df = pd.DataFrame(mydict)
plt.plot(df['time'], df['b'])
plt.show()
1 Answers

You can use pd.to_datetime to convert epoch time to datetime format when plotting. Then to ensure the format of the xticks, you can use dt.strftime.

plt.plot(pd.to_datetime(df['time'], unit='s').dt.strftime('%Y-%m-%d %H:%M'), df['b'])
plt.show()
Related