Part 08 / Topic 9 of 10
Dates and times in files
Files store text, so dates must be turned into text and back.
- ISO format (the international standard, ISO 8601)
2025-03-10T09:30:00is the best choice: clear, sortable as plain text, and Python reads it back easily. - Use
strptimefor other formats like10/03/2025. datetime.now()includes microseconds (09:05:00.482913).isoformat(timespec="seconds")cuts the text at whole seconds, which is neater in a log.
Real-world example: a timestamped attendance log.
from datetime import datetime
check_in = datetime(2025, 3, 10, 9, 5)
line = f"{check_in.isoformat(timespec='seconds')} | Asha | IN"
print(line) # 2025-03-10T09:05:00 | Asha | IN
stamp = line.split(" | ")[0]
back = datetime.fromisoformat(stamp) # text -> datetime
print(back.strftime("%d %b %Y, %I:%M %p")) # 10 Mar 2025, 09:05 AM
typed = datetime.strptime("10/03/2025 17:35", "%d/%m/%Y %H:%M")
print(typed - back) # 8:30:00 (a timedelta)
| Want | Use |
|---|---|
| datetime → ISO text | dt.isoformat(timespec="seconds") |
| ISO text → datetime | datetime.fromisoformat(text) |
| Any text → datetime | datetime.strptime(text, "%d/%m/%Y %H:%M") |
| datetime → any text | dt.strftime("%d %b %Y") |
| Right now | datetime.now() |
See examples/06_attendance_log.py.
🔍 Going deeper: these datetimes are naive (no time zone). For logs shared across places, save UTC with an offset:
datetime.now(timezone.utc).isoformat()gives text like2025-03-10T03:35:00+00:00, andfromisoformatreads the offset back. Usetd.total_seconds()on atimedelta;td.secondsignores whole days.
Done here? The practice set for Part 8 — 8 exercises with solutions — is on the part page.