Python 如何整理 CSV 中格式混亂的日期
Normalize Messy Dates in a CSV With Python
教程示範如何用 Python 將 CSV 日期整理為 YYYY-MM-DD,同時保留原始欄位,並將結果寫入新欄。程式只轉換事先約定的三種格式;歧義的斜線日期、無效日期、空值及不支援格式則記錄在 date_status,不作猜測。教程亦建議向來源確認被標記的資料,只有確定來源日期格式後才加入斜線日期規則。
Disclosure: I wrote this tutorial with AI assistance. I work with ExtractHelp, a data services agency. The code below is self-contained and uses fictional sample data.
Messy dates cause quiet CSV problems. One row says 2026-11-27. Another says 27 Nov 2026. A third says 06/07/2026, which could mean 6 July or June 7. If you sort or import those values as text, the order can be wrong and the import can fail.
The safe rule is simple: convert only formats you have agreed in advance. Write the result to a new column. Flag anything ambiguous, invalid, or unsupported instead of guessing.
The target format
Use YYYY-MM-DD as the target date format. It sorts correctly as text and is clear to read. Keep the original value in its own column, so you can always check what changed.
This tutorial accepts three agreed input formats:
2026-11-2727 Nov 2026November 27, 2026
Slash dates such as 06/07/2026 are flagged as ambiguous. They are not converted unless the source format is known and added on purpose.
Step 1: Write the normalizer
Save this as normalize_dates.py.
import csv
import re
from datetime import datetime
AGREED_FORMATS = ("%Y-%m-%d", "%d %b %Y", "%B %d, %Y")
SLASH_DATE = re.compile(r"^\d{1,2}/\d{1,2}/\d{4}$")
ISO_LIKE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
def normalize_date(value):
text = (value or "").strip()
if not text:
return "", "empty"
if SLASH_DATE.match(text):
return "", "ambiguous slash date"
for fmt in AGREED_FORMATS:
try:
parsed = datetime.strptime(text, fmt).date()
return parsed.isoformat(), "converted"
except ValueError:
pass
if ISO_LIKE.match(text):
return "", "invalid date"
return "", "unsupported format"
def main(input_path="orders.csv", output_path="orders_normalized.csv"):
with open(input_path, newline="", encoding="utf-8-sig") as source:
reader = csv.DictReader(source)
fieldnames = list(reader.fieldnames or []) + ["normalized_date", "date_status"]
rows = []
for row in reader:
normalized, status = normalize_date(row.get("order_date", ""))
row["normalized_date"] = normalized
row["date_status"] = status
rows.append(row)
with open(output_path, "w", newline="", encoding="utf-8") as target:
writer = csv.DictWriter(target, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(rows)
if __name__ == "__main__":
main()
The important part is the status column. A converted date gets converted. A risky date gets a reason. That reason tells the next person what to check.
Step 2: Test with fictional rows
Use a small fictional file first:
order_id,order_date
A100,2026-11-27
A101,27 Nov 2026
A102,"November 27, 2026"
A103,06/07/2026
A104,2026-02-30
A105,
The output keeps order_date unchanged and adds two columns:
order_id,order_date,normalized_date,date_status
A100,2026-11-27,2026-11-27,converted
A101,27 Nov 2026,2026-11-27,converted
A102,"November 27, 2026",2026-11-27,converted
A103,06/07/2026,,ambiguous slash date
A104,2026-02-30,,invalid date
A105,,,empty
This is the behaviour you want. Known formats become YYYY-MM-DD. Risky values are visible instead of silently guessed.
Step 3: Decide what to do with flagged rows
Flagged rows need a decision. Ask the source owner which format was used, fix the source export, or keep those rows out of the import until they are confirmed.
Do not add a slash format just to make the file pass. Add %d/%m/%Y or %m/%d/%Y only when the source format is known for that file. If two sources use different slash orders, split them before converting.
Common mistakes
-
Guessing slash dates.
06/07/2026can be read two ways. - Overwriting the original column. Keep the original value beside the normalized one.
- Using one format list for every source. Agree formats per source and per field.
-
Treating invalid dates as empty.
2026-02-30is not a real date and should be reported. - Sorting before normalizing. Mixed text dates do not sort like real dates.
Conclusion
Normalize dates by agreement, not by guesswork. Convert known formats to YYYY-MM-DD, write the result to a new column, and flag ambiguous, invalid, empty, or unsupported values with a reason.
That pattern matches ExtractHelp’s Data Formatting service: a target format is agreed for each field, original values are kept, and ambiguous values are flagged instead of guessed. If the file also needs rule checks before import, see Data Validation.
來源:DEV Community · dev.to