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

วิธีทำ Date Validation ใน Python

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() รองรับ:

DirectiveMeaning
%aAbbreviated weekday name
%AFull weekday name
%bAbbreviated month name
%BFull month name
%cDate and time representation
%dDay of month [01,31]
%HHour 24-hour [00,23]
%IHour 12-hour [01,12]
%jDay of year [001,366]
%mMonth [01,12]
%MMinute [00,59]
%pAM/PM
%SSecond [00,61]
%UWeek number (Sun first) [00,53]
%wWeekday [0(Sun),6]
%WWeek number (Mon first) [00,53]
%xDate representation
%XTime representation
%yYear without century [00,99]
%YYear with century
%ZTime zone name
%%Literal % character