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

วิธีแปลง JS Date เป็น Python Date Object


เมื่อส่งข้อมูลวันที่จาก JavaScript ไป Python (ผ่าน AJAX, API, IPC) มักจะส่งในรูป String รูปแบบมาตรฐานคือ ISO 8601 (เช่น '2017-12-31' หรือ '2017-12-31T10:30:00Z') Python ใช้ datetime.strptime() แปลง String กลับเป็น datetime Object

ตัวอย่าง Python Code

import datetime

# String ที่ได้จาก JavaScript (ISO 8601 format)
date_string = '2017-12-31'
date_format = '%Y-%m-%d'

try:
    date_obj = datetime.datetime.strptime(date_string, date_format)
    print(date_obj)  # 2017-12-31 00:00:00
except ValueError:
    print("Incorrect data format, should be YYYY-MM-DD")

ผลลัพธ์

2017-12-31 00:00:00

Directive ตัวสำคัญของ strptime()

Directiveความหมายตัวอย่าง
%YYear with century2017
%yYear without century17
%mMonth (01-12)12
%dDay (01-31)31
%HHour 24h (00-23)14
%IHour 12h (01-12)02
%MMinute (00-59)30
%SSecond (00-61)59
%fMicrosecond (000000-999999)123456
%zUTC Offset+0700
%ZTimezone NameICT
%AWeekday Full NameSunday
%aWeekday AbbreviatedSun
%BMonth Full NameDecember
%bMonth AbbreviatedDec
%cLocale Date & TimeSun Dec 31 10:30:00 2017
%xLocale Date12/31/2017
%XLocale Time10:30:00
%%Literal %%

รูปแบบวันที่ที่นิยมใช้

# ISO 8601 (แนะนำ - มาตรฐานสากล)
'2017-12-31'           # Date only
'2017-12-31T10:30:00'  # Local time
'2017-12-31T10:30:00Z' # UTC (Zulu)
'2017-12-31T10:30:00+07:00' # With timezone

# Python parsing
datetime.fromisoformat('2017-12-31')           # Python 3.7+
datetime.fromisoformat('2017-12-31T10:30:00')  # Python 3.7+
datetime.fromisoformat('2017-12-31T10:30:00+07:00') # Python 3.11+

JavaScript Side: สร้าง ISO String

const date = new Date();
date.toISOString();        // "2017-12-31T10:30:00.000Z" (UTC)
date.toISOString().split('T')[0]; // "2017-12-31" (Date only)

// หรือใช้ toLocaleDateString สำหรับ Format เฉพาะ Locale
date.toLocaleDateString('en-CA'); // "2017-12-31" (ISO-like)

Best Practices

  • ใช้ ISO 8601 (toISOString) เป็นมาตรฐานสื่อสารระหว่าง JS ↔ Python
  • ส่ง UTC Timezone (Z) เสมอ หลีกเลี่ยงปัญหา Timezone
  • Python 3.7+ ใช้ datetime.fromisoformat() ได้เลย (ไม่ต้อง strptime)
  • Handle Error ด้วย try/except ValueError
  • พิจารณา dateutil.parser.parse() สำหรับ Parse รูปแบบหลากหลาย (Third-party)