Python Intermediate Lesson 4: Dates, Formats and the Indian Financial Year

Python Intermediate Lesson 4: Dates, Formats and the Indian Financial Year 1

πŸ“Ž This article includes 3 downloadable practice files ↓

⏱ 2 min read

πŸ“˜ Python Intermediate Course Β· Lesson 4 of 10

Advertisement
In this article
  1. Financial year helpers
  2. Working days with holidays
  3. Common mistakes
  4. Practice
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: %m is month, %M is 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

Leave a Reply

Your email address will not be published. Required fields are marked *