เมื่อส่งข้อมูลวันที่จาก 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 | ความหมาย | ตัวอย่าง |
|---|---|---|
%Y | Year with century | 2017 |
%y | Year without century | 17 |
%m | Month (01-12) | 12 |
%d | Day (01-31) | 31 |
%H | Hour 24h (00-23) | 14 |
%I | Hour 12h (01-12) | 02 |
%M | Minute (00-59) | 30 |
%S | Second (00-61) | 59 |
%f | Microsecond (000000-999999) | 123456 |
%z | UTC Offset | +0700 |
%Z | Timezone Name | ICT |
%A | Weekday Full Name | Sunday |
%a | Weekday Abbreviated | Sun |
%B | Month Full Name | December |
%b | Month Abbreviated | Dec |
%c | Locale Date & Time | Sun Dec 31 10:30:00 2017 |
%x | Locale Date | 12/31/2017 |
%X | Locale Time | 10: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)