Date Validation ขึ้นอยู่กับ Format ของ Date ที่มี ฟังก์ชัน strptime จาก datetime Library ใช้ Parse String เป็น Date/Time
ตัวอย่าง
import datetime
date_string = '2017-12-31'
date_format = '%Y-%m-%d'
try:
date_obj = datetime.datetime.strptime(date_string, date_format)
print(date_obj)
except ValueError:
print("Incorrect data format, should be YYYY-MM-DD")
ผลลัพธ์
2017-12-31 00:00:00
Directives ที่ strptime() รองรับ:
| Directive | Meaning |
|---|---|
| %a | Abbreviated weekday name |
| %A | Full weekday name |
| %b | Abbreviated month name |
| %B | Full month name |
| %c | Date and time representation |
| %d | Day of month [01,31] |
| %H | Hour 24-hour [00,23] |
| %I | Hour 12-hour [01,12] |
| %j | Day of year [001,366] |
| %m | Month [01,12] |
| %M | Minute [00,59] |
| %p | AM/PM |
| %S | Second [00,61] |
| %U | Week number (Sun first) [00,53] |
| %w | Weekday [0(Sun),6] |
| %W | Week number (Mon first) [00,53] |
| %x | Date representation |
| %X | Time representation |
| %y | Year without century [00,99] |
| %Y | Year with century |
| %Z | Time zone name |
| %% | Literal % character |