How to Validate a Given Date in Python


In this example we will show how to check the validation of the given date (e.g. day, month, and year) in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

date = input("Enter the date(dd/mm/yyyy): ")
dd,mm,yy = date.split("/")
dd = int(dd)
mm = int(mm)
yy = int(yy)
mm30 = [4, 6, 9, 11]
mm31 = [1, 3, 5, 7, 8, 10, 12]
if mm in mm30:
    ddMax = 30
elif mm in mm31:
    ddMax = 31
elif yy % 4 == 0 and yy % 100 != 0 or yy % 400 == 0:
    ddMax=29
else:
    ddMax=28
if dd < 1 or dd > ddMax:
    print("Date is invalid.")
elif mm < 1 or mm > 12:
    print("Date is invalid.")
else:
    print("Date is valid.")

Output:

Enter the date(dd/mm/yyyy): 35/8/2018
Date is invalid.

Enter the date(dd/mm/yyyy): 25/3/2019
Date is valid.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments