PART 2 · PYTHON FOUNDATIONS · CHAPTER 2
Numbers, strings and dates that bite
FreeLesson 25 of 78
Money, text encodings and time zones break more pipelines than any algorithm. Each one has a single rule to remember.
from decimal import Decimal, ROUND_HALF_UP
print(0.1 + 0.2, 0.1 + 0.2 == 0.3)
print(Decimal("0.1") + Decimal("0.2"))
print(Decimal(0.1)) # from a float: too late
print(round(2.5), round(3.5)) # banker's rounding
price = Decimal("2.675")
print(price.quantize(Decimal("0.01"), ROUND_HALF_UP))
print(7 // 2, -7 // 2, int(-3.5)) # floor vs truncOutput
0.30000000000000004 False 0.3 0.1000000000000000055511151231257827021181583404541015625 2 4 2.68 3 -4 -3
status = " DELIVERED \n"
print(repr(status.strip().lower()))
amount = 1198.5
print(f"{amount:,.2f} | {amount:>10.1f} | {0.256:.1%}")
parts = "101,1,2025-01-10,delivered,1198.00".split(",")
print(parts[3], "|".join(parts[:2]))
word = "café"
print(word, len(word), len(word.encode("utf-8")))Output
'delivered' 1,198.50 | 1198.5 | 25.6% delivered 101|1 café 4 5
from datetime import date, datetime, timedelta, timezone
from zoneinfo import ZoneInfo
d = datetime.strptime("2025-04-01 10:00", "%Y-%m-%d %H:%M")
print(d.isoformat(), d.tzinfo) # naive
ist = d.replace(tzinfo=ZoneInfo("Asia/Kolkata"))
print(ist.astimezone(timezone.utc).isoformat())
print(date(2025, 3, 31) + timedelta(days=1))
print((date(2025, 4, 28) - date(2025, 3, 12)).days)
print(d.strftime("%Y-%m"), d.weekday()) # Monday = 0Output
2025-04-01T10:00:00 None 2025-04-01T04:30:00+00:00 2025-04-01 47 2025-04 1
Practice before you move on
- Add up the amount column of orders.csv once as float and once as Decimal, and compare the two totals.
- Parse every order_date into a date and print the weekday of the first and the last order.