Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

โปรแกรมแปลงรูปแบบวันที่เป็น YYYY-MM-DD ใน Python


ภาพรวม

แปลงวันที่รูปแบบ "Day Month Year" (เช่น "23rd Jan 2021") เป็นรูปแบบมาตรฐาน ISO "YYYY-MM-DD" (เช่น "2021-01-23")

รูปแบบอินพุต

  • วัน: 1st, 2nd, 3rd, ..., 31st (มี hậu tố st, nd, rd, th)
  • เดือน: Jan, Feb, Mar, ..., Dec (ย่อ 3 ตัวอักษร)
  • ปี: 4 หลัก (1900-2100)

ขั้นตอนการแก้ปัญหา

  1. สร้างลิสต์ชื่อเดือน Months
  2. แยกสตริงด้วย split() ได้ [day, month, year]
  3. ดึงปี: year = string[2]
  4. ดึงวัน: ตัดท้าย 2 ตัวอักษร (หลัก st/nd/rd/th) → day = string[0][:-2]
  5. ถ้าวันเป็น 1 หลัก ให้เติม '0' นำหน้า
  6. หาเลขเดือนจากลิสต์ Months (index + 1)
  7. ถ้าเดือนเป็น 1 หลัก ให้เติม '0' นำหน้า
  8. จัดรูปแบบ f"{year}-{month}-{day}"

ตัวอย่างโค้ด (Python)

def solve(date):
    Months = ["Jan","Feb","Mar","Apr","May","Jun",
              "Jul","Aug","Sep","Oct","Nov","Dec"]
    string = date.split()
    year = string[2]
    day = string[0][:-2]
    if len(day) < 2:
        day = "0" + day
    month = str(Months.index(string[1]) + 1)
    if len(month) < 2:
        month = "0" + month
    return f"{year}-{month}-{day}"

date = "23rd Jan 2021"
print(solve(date))

อินพุต

"23rd Jan 2021"

เอาต์พุต

2021-01-23

วิธีทางเลือก (datetime)

ใช้ datetime.strptime พร้อมรูปแบบ "%d%b %Y" แล้ว strftime("%Y-%m-%d") จะจัดการ hậu tốวันอัตโนมัติ