Is there a data type for handling dates in python?
No. Python does not provides any special data type for handling dates in Python. But that does not mean, you can’t play with dates while programming in Python. In this post you will learn:
- What is Python module -datetime?
- How to format dates in Python?
- How to validate dates in Python?
Python Module – datetime
Python provides full functionality for handling dates with the help of classes through the module – datetime. You simply have to give the command:
import datetime
Accepting date, in python is quite simple, observe the code below:
import datetime JoiningDate = input("Enter the date in format 'dd/mm/yy' : ") print(JoiningDate)
Formatting Dates in Python
At times we need to display Dates in different styles, extract only month or year from it. Python’s datetime module allows you to format dates in the style you want. Look at the code below:
import datetime x = datetime.datetime(2020, 3, 23) print(x.day, "/",x.month,"/",x.year)
will produce the output as:
23/3/2020
While handling dates in python, you can format it further, observe the code below:
import datetime x = datetime.datetime(2020, 3, 23) print(x.day, "-",x.strftime("%B"),"-",x.year)
will produce the output:
23-March-2020
Validating Dates in Python
The code above is not even utilizing the module datetime for handling dates in Python for formatting or validating purposes. But we can use this module to do various operations on dates. The code below describes how you can validate (check if the entered date is correct or not). You can check, the date entered by the user is a valid date or not.
For example : 32-14-2020 is not a valid date, since we cannot have a day 32 and month 14, though this was quite lame. But at times we need to validate dates. Look at the code below:
# importing module import datetime //Taking date input as a normal string JoiningDate = input("Enter the date ['dd/mm/yy'] : ") # Splitting date entered into separate units Day (D), Month(M) # and Year(Y) using separator "/" D,M,Y = JoiningDate.split('/') # An indicator variable CHK initialised to True CHK = True # With the Help of exception handling try : datetime.datetime(int(Y),int(M),int(D)) # raises exception if date entered is wrong, and goes to except block except ValueError : CHK= False # initialised to false if exception is raised if(CHK) : print ("Valid Date") else : print ("Invalid Date Entered!!!")
Python provides methods to handle different types of errors. One such feature is to handle unexpected or unforeseen errors called exceptions.
Python is an Object Oriented Language, thus provides various classes and events to handle so many things. Exception is also an event that occurs when unexpected error occurs during the execution of the program. We place the code, that we expect might produce unexpected error inside (indented block) a try: block:
try: //code goes here
It does not terminates a program abruptly, rather passes the control to except: statement, which takes the control.