Home > Back-end >  How to save matplotlib plot with a custom filename that includes timestamp?
How to save matplotlib plot with a custom filename that includes timestamp?

Time:05-21

I'm trying to write a program in Python which can save a plot with a filename that includes the timestamp as part of its name with matplotlib, for example, "temperature_vs_time_16-09-23". I tried using an fstring and time.strftime('format', time.time()) but it doesn't seem to be working. Does anyone have an easy work around for this? Thanks.

CodePudding user response:

You can use datetime and join strings as filename

import matplotlib.pyplot as plt
import numpy as np
from datetime import datetime
values = np.random.randint(0,10,100)
now = datetime.now()
today_filename = "temperature_vs_time_" now.strftime("%d-%m-%Y") ".png"
plt.plot(values)
plt.savefig(today_filename)

CodePudding user response:

You can try this way by using pandas to get current datetime, it should work

date = pd.to_datetime('now').strftime("%Y-%m-%d")

### Filename of your choice
filename = 'temp_{name}'.format(name=date)

### Visualize
plt.plot(df['column'].value_counts())

### Save figure
plt.savefig(filename '.jpg', dpi=100)

plt.show()
  • Related