Wie konvertiere ich nicht standardmäßige Datumsformate für die Darstellung in Python?

Patricia Arquette
Freigeben: 2024-10-17 13:48:30
Original
362 Leute haben es durchsucht

How to Convert Non-Standard Date Formats for Plotting in Python?

Converting Dates to Plottable Format

Plotting data against dates can be challenging when dates are stored in non-standard formats. In the given case, the date format is "01/02/1991". To simplify the plotting process, we can convert these dates into a format acceptable by the plot function of matplotlib.

To begin, convert the strings into instances of Python datetime.date:

<code class="python">import datetime as dt

dates = ['01/02/1991','01/03/1991','01/04/1991']
x = [dt.datetime.strptime(d,'%m/%d/%Y').date() for d in dates]</code>
Nach dem Login kopieren

The next step is to plot the data. Instead of using plot_date(), which encountered the error, we can use the simpler plot() instead:

<code class="python">import matplotlib.pyplot as plt
import matplotlib.dates as mdates

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%m/%d/%Y'))
plt.gca().xaxis.set_major_locator(mdates.DayLocator())
plt.plot(x,y)
plt.gcf().autofmt_xdate()</code>
Nach dem Login kopieren

By following these steps, you can now plot your information effectively against dates in the desired format.

Das obige ist der detaillierte Inhalt vonWie konvertiere ich nicht standardmäßige Datumsformate für die Darstellung in Python?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!

Quelle:php
Erklärung dieser Website
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Neueste Artikel des Autors
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!