Aller au contenu

Leçon 15 · Types, Text and Dates

Cleaning Dates and Times

Clean messy dates: parse known formats, resolve day-month ambiguity, convert spreadsheet serial numbers and handle time zones and daylight saving safely.

Dates look familiar, so their errors slip through. 03/04/2026 is 3 April to some people and 4 March to others. A timestamp with no time zone may be hours off. This lesson shows how to parse dates without guessing.

Store dates in one form

For text storage and exchange, use the ISO 8601 style: 2026-03-04 for dates and 2026-03-04T14:30:00+00:00 for timestamps. It is unambiguous, and values in exactly the same format (and, for timestamps, the same offset) sort correctly as text. In programs and databases, use real date types where they exist.

Parse with explicit formats

Python's datetime module parses with strptime and a format you choose.

Python Parse with a list of known formats

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

31/02/2026 fails because that day does not exist, which is helpful. 12/25/2026 fails because this source is day-first. If you had added %m/%d/%Y as a fallback, the parser would read some values one way and some the other, depending on which happened to work.

Resolve ambiguity with evidence

In slash dates, a first number above 12 can only be a day. A second number above 12 can only mean month-first order. This can reveal a source's convention, but it cannot prove the format of ambiguous rows if the file mixes sources.

Python Look for format evidence

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

If both proof counts are above zero, the column mixes formats. Split by source or ask the provider. Other clues include file dates and whether any dates fall impossibly in the future.

Two-digit years

01/02/03 is hard to read at all. Two-digit years force a guess about the century. Python's %y applies a fixed pivot rule, which may not suit birth dates. Set your own rule and flag results that look implausible.

Spreadsheet serial numbers

Spreadsheets often store dates as a count of days. A column may then show values like 46000. For Excel's 1900 date system, and for Google Sheets serial numbers, you can usually convert with a base date of 30 December 1899. Excel also supports a 1904 date system with a different base. Excel's 1900 system also wrongly treats 1900 as a leap year, so for Excel serial numbers this shortcut is wrong for dates before 1 March 1900.

Python Convert spreadsheet serial numbers

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check some converted values against what the spreadsheet shows.

Time zones

A naive timestamp has no time zone information, while an aware one does. Find out what each source uses. A common approach is to store instants in UTC and keep the original zone if local time matters, for example for "sales by local hour".

Python Convert offsets to UTC

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

An offset such as +01:00 is not a full time zone. Zone names such as Europe/Paris carry daylight saving rules, and Python's zoneinfo module uses them when time zone data is available. Where clocks change, some local times occur twice and some never occur. Do not attach UTC to a naive time just to silence an error: that can shift its meaning.

Birthdays and holidays are calendar dates, not instants. Do not convert them between zones, or they can move to another day.

Check plausibility

After parsing, test rules: no order before the company opened, no birth date in the future, no ship date before the order date. Pile-ups on 1900-01-01, 1970-01-01 or the first day of months can suggest defaults.

pandas

Python pandas: parse with a format and inspect failures

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Pass format= whenever you know it. With format="mixed", pandas infers the format for each value separately, which can read rows differently. See dates and times in pandas.

Common mistake: some dates fail to parse, so you add formats until nothing fails. Zero failures can mean that some values were read wrongly.

Intervals and boundaries

Cleaning often feeds questions such as "sales in March". With timestamps, a safe pattern is to include the start and exclude the next period's start: at or after 1 March and before 1 April. A condition that ends at "31 March" may leave out most of that last day, because a bare date can be read as midnight at its start.

Also ask which time zone defines the day. A sale late in the evening in one country is already the next day in UTC or farther east. Choose the reporting zone, convert first, then take the date.

Partial dates

Some records know only a year or a month. Turning 2026-03 into 2026-03-01 invents a day, and later analysis may treat it as real. Keep the original text, and if you must store a full date, add a precision column with values such as day, month or year.

A routine for date columns

  1. List the shapes in the column, as in the profiling lesson.
  2. Find the documented format for each source.
  3. Parse source by source, with explicit formats.
  4. Report every non-empty value that failed.
  5. Check the minimum, maximum and the distribution by month.
  6. Compare a few results with the original system.

A monthly chart is a surprisingly good test. If swapped days and months slipped through, you may see records spread into months where the business had no activity, or odd peaks on early days of the month. A normal-looking chart does not prove that every date is right, though, so keep the explicit format rules.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. Why is adding both day-first and month-first formats as fallbacks risky?

    A value like 03/04 fits both, so the order of attempts silently decides its meaning.
  2. 2. What does a naive datetime lack?

    Without a zone or offset, it does not identify one exact instant.
  3. 3. Why not convert birthdays between time zones?

    A birthday names a day on the calendar, not a moment in time.

Summary

  • Parse with documented formats, per source.
  • Treat ambiguity as a question, not a guess.
  • Know your spreadsheet date system.
  • Make timestamps time zone aware, and leave calendar dates alone.
  • Check plausibility after parsing.

Next: Detecting and Handling Outliers

Votre progression est enregistrée dans ce navigateur. Aucun compte nécessaire.