Analizzare stringhe come datetime
to_datetime e gestione dei formati.
Analizzare stringhe come datetime è una lezione Data Science Academy gratuita su CoddyKit. Questa è la lezione 1 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Data Science Academy, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Data Science Academy include 4 lezioni in totale.
Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.
Dates Hide as Text
When you load a CSV, dates usually arrive as plain strings. They look right but pandas treats them as text, so date math just won't work yet. 📅
Enter to_datetime
The fix is one function: pd.to_datetime. It scans your text and turns each value into a real timestamp pandas can compute with.
import pandas as pd
ts = pd.to_datetime("2024-03-15")
print(ts)Convert a Whole Column
Pass a Series and you get back a column of timestamps. This is the everyday move right after loading a table with a date field.
df["date"] = pd.to_datetime(df["date"])Check the dtype
After converting, the column's dtype becomes datetime64. That single check tells you the parse actually worked and date math is now unlocked.
print(df["date"].dtype) # datetime64[ns]Many Formats, One Call
to_datetime is smart: it reads ISO dates, slashes, and even written months automatically. For tidy ISO strings you rarely need to tell it anything else.
pd.to_datetime(["2024-01-01", "Jan 2, 2024"])Spell Out the Format
When dates are ambiguous, give an explicit format string. It removes guessing and runs much faster on big columns.
pd.to_datetime("15/03/2024", format="%d/%m/%Y")Day-First Dates
Is 03/04 March or April? Set dayfirst=True so pandas reads the day before the month, matching most European date styles.
pd.to_datetime("03/04/2024", dayfirst=True)Bad Values Without Crashing
One messy cell can break a whole parse. Use errors="coerce" to turn unparseable values into NaT instead of raising an error.
pd.to_datetime("not-a-date", errors="coerce") # NaTMeet NaT
NaT is the datetime version of NaN: a missing timestamp. You can spot these failed parses with isna and decide how to handle them.
df["date"].isna().sum() # count failed parsesCombine Date and Time Parts
Have separate date and hour columns? Concatenate them into one string, then parse once. You end up with a single clean timestamp.
pd.to_datetime(df["day"] + " " + df["time"])Parse at Read Time
You can skip a step by parsing during import. Pass parse_dates to read_csv and the column arrives as datetimes already.
pd.read_csv("sales.csv", parse_dates=["date"])Quick Check
Your date column has a few junk values you want to keep as missing.
Recap: You Can Parse Dates
You turned text into real timestamps with pd.to_datetime, controlled formats, handled bad values with coerce, and even parsed on load. Date math is now within reach. 🎉
Domande Frequenti
La lezione «Analizzare stringhe come datetime» è gratuita?
Sì — il testo completo di «Analizzare stringhe come datetime» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Data Science Academy, passa a CoddyKit PRO. Il corso Data Science Academy include 4 lezioni in totale.
Cosa imparerò in «Analizzare stringhe come datetime»?
to_datetime e gestione dei formati. Eserciti Data Science Academy con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.
Ho bisogno di esperienza per iniziare Data Science Academy?
Non è richiesta alcuna esperienza precedente. Data Science Academy su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 1 di 4.
Quanto tempo richiede la lezione «Analizzare stringhe come datetime»?
La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.
Posso scrivere ed eseguire codice in questa lezione Data Science Academy?
Sì. Ogni lezione Data Science Academy include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.
Tutte le lezioni di questo corso
- Analizzare stringhe come datetime
- Estrarre anno, mese e giorno della settimana
- Ricampionare su base giornaliera o mensile
- Fusi orari e intervalli di date