Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Validate date trong Python

Date validation phụ thuộc format date. Dùng strptime từ datetime để parse string thành date/time.

Ví dụ

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)  # 2017-12-31 00:00:00
except ValueError:
    print("Incorrect data format, should be YYYY-MM-DD")

Kết quả

2017-12-31 00:00:00

Các directive phổ biến của strptime

DirectiveMeaning
%YYear with century (2024)
%mMonth [01,12]
%dDay [01,31]
%HHour 24h [00,23]
%MMinute [00,59]
%SSecond [00,61]
%fMicrosecond [000000,999999]
%zUTC offset (+HHMM/-HHMM)
%ZTimezone name