Datetime & Money
Datetime & Money
Section titled “Datetime & Money”วันที่และเงินเป็น 2 ชนิดข้อมูลที่ต้องจัดการอย่างระมัดระวังเป็นพิเศษ ผิดพลาดเล็กน้อยอาจนำไปสู่ bug ที่หาสาเหตุยาก
pd.to_datetime() — แปลง string เป็น datetime
Section titled “pd.to_datetime() — แปลง string เป็น datetime”import pandas as pd
df = pd.DataFrame({ "order_date": ["2024-01-15", "2024-02-20", "15/03/2024", "April 10, 2024"], "amount": [500.00, 1200.50, 350.75, 899.99]})
# แปลงรูปแบบเดียวdf["order_date"] = pd.to_datetime(df["order_date"], format="mixed")
# กำหนด format เฉพาะ (เร็วกว่า)dates = pd.to_datetime(["15/01/2024", "20/02/2024"], format="%d/%m/%Y").dt accessor — ดึงส่วนประกอบของวันที่
Section titled “.dt accessor — ดึงส่วนประกอบของวันที่”df["year"] = df["order_date"].dt.yeardf["month"] = df["order_date"].dt.monthdf["day"] = df["order_date"].dt.daydf["day_name"] = df["order_date"].dt.day_name() # Monday, Tuesday...df["quarter"] = df["order_date"].dt.quarter # 1, 2, 3, 4df["week"] = df["order_date"].dt.isocalendar().week
# คำนวณระยะเวลาdf["days_ago"] = (pd.Timestamp.now() - df["order_date"]).dt.daysกรองด้วยวันที่
Section titled “กรองด้วยวันที่”# ข้อมูลเดือนมกราคมjan = df[df["order_date"].dt.month == 1]
# ข้อมูลตั้งแต่ 1 ก.พ. เป็นต้นไปafter_feb = df[df["order_date"] >= "2024-02-01"]
# ข้อมูลช่วงเวลาmask = (df["order_date"] >= "2024-01-01") & (df["order_date"] <= "2024-03-31")q1 = df[mask]Decimal — จัดการเงินอย่างถูกต้อง
Section titled “Decimal — จัดการเงินอย่างถูกต้อง”# ปัญหาของ floatprint(0.1 + 0.2) # 0.30000000000000004 !!!print(0.1 + 0.2 == 0.3) # False !!!
# แก้ด้วย Decimalfrom decimal import Decimal
a = Decimal("0.1")b = Decimal("0.2")print(a + b) # 0.3print(a + b == Decimal("0.3")) # True
# ใช้กับราคาสินค้าprice = Decimal("199.99")tax = price * Decimal("0.07")total = price + taxprint(f"ราคารวม VAT: {total}") # 213.9893total = total.quantize(Decimal("0.01")) # ปัดเศษ 2 ตำแหน่งprint(f"ราคารวม VAT: {total}") # 213.99Resample — สรุปข้อมูลตามช่วงเวลา
Section titled “Resample — สรุปข้อมูลตามช่วงเวลา”# สรุปยอดขายรายเดือนdf = df.set_index("order_date")monthly = df["amount"].resample("ME").sum()print(monthly)- วันที่: Google Sheets จัดการ date ได้ดี —
=YEAR(A1),=MONTH(A1) - เงิน: Format > Number > Currency
- ปัญหา float เดียวกัน แต่ซ่อนด้วย display format
-- DatetimeEXTRACT(YEAR FROM order_date)DATE_TRUNC('month', order_date)-- Money (PostgreSQL)NUMERIC(10,2) -- ไม่ใช่ FLOAT!#include <time.h>struct tm t;strptime("2024-01-15", "%Y-%m-%d", &t);// เงิน: ใช้ int เก็บเป็นสตางค์ (199.99 → 19999)