
π This article includes 3 downloadable practice files β
Advertisement
| Need | Code |
|---|---|
| Text β date | dt.datetime.strptime("04-10-2026", "%d-%m-%Y").date() |
| ISO text β date | dt.date.fromisoformat("2026-10-04") |
| Date β text | d.strftime("%d %b %Y") β 04 Oct 2026 |
| Weekday | d.strftime("%A"), or d.weekday() (Mon = 0) |
| Add days | d + dt.timedelta(days=30) |
Financial year helpers
def fy_label(d):
y = d.year - (d.month < 4)
return f"FY {y}-{str(y + 1)[2:]}" # 2026-10-04 -> FY 2026-27
def fy_quarter(d):
return f"Q{(d.month - 4) % 12 // 3 + 1}" # Apr-Jun = Q1
Working days with holidays
def add_working_days(d, n, holidays=()):
while n:
d += dt.timedelta(days=1)
if d.weekday() < 5 and d not in holidays:
n -= 1
return d
For whole calendars, numpy.busday_offset and pandas’ CustomBusinessDay do the same on millions of dates.
π‘ Month end without extra libraries: go to the 28th, add 4 days (always next month), go to the 1st, subtract a day.
Common mistakes
- %m vs %M:
%mis month,%Mis minutes. - Comparing a date with a datetime raises TypeError; convert with
.date().
Practice
Unzip the practice data into a folder, put this lesson’s script in the same folder and run it (python pyi-NN.py). Compare with the expected output file. Then change one thing (a filter, a column, a format) and predict the new output before you run it.
π Practice files for this article
β¬ Download all 3 files (ZIP Β· 4 KB)
- πLesson 4 scriptThe complete script from this lesson, ready to run.β¬ PY Β· 1 KB
- πExpected outputWhat the script printed when we ran it, to compare with yours.β¬ TXT Β· 288 B
- ποΈPractice data (zip)sales.csv (120 invoices, 2 deliberately broken rows), customers.csv, products.json, statement.txt, rates.json and 3 monthly CSVs.β¬ ZIP Β· 4 KB
Free to use for learning. Files with macros (.bas) are plain text β import them with Alt+F11 β File β Import File, and always test on a copy.
β¨ Ask AI about this article
Stuck on a step? Ask a question and the AI answers using this article.
Free Β· AI can be wrong