Skip to content

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.year
df["month"] = df["order_date"].dt.month
df["day"] = df["order_date"].dt.day
df["day_name"] = df["order_date"].dt.day_name() # Monday, Tuesday...
df["quarter"] = df["order_date"].dt.quarter # 1, 2, 3, 4
df["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 — จัดการเงินอย่างถูกต้อง”
# ปัญหาของ float
print(0.1 + 0.2) # 0.30000000000000004 !!!
print(0.1 + 0.2 == 0.3) # False !!!
# แก้ด้วย Decimal
from decimal import Decimal
a = Decimal("0.1")
b = Decimal("0.2")
print(a + b) # 0.3
print(a + b == Decimal("0.3")) # True
# ใช้กับราคาสินค้า
price = Decimal("199.99")
tax = price * Decimal("0.07")
total = price + tax
print(f"ราคารวม VAT: {total}") # 213.9893
total = total.quantize(Decimal("0.01")) # ปัดเศษ 2 ตำแหน่ง
print(f"ราคารวม VAT: {total}") # 213.99

Resample — สรุปข้อมูลตามช่วงเวลา

Section titled “Resample — สรุปข้อมูลตามช่วงเวลา”
# สรุปยอดขายรายเดือน
df = df.set_index("order_date")
monthly = df["amount"].resample("ME").sum()
print(monthly)