Working With Dates in Python
In this article, we will discuss how to work with dates using python.
Python makes dealing with dates and time very easy, all we have to do is import a module named DateTime that comes along with python. It is a more efficient way to work with date without the need of being explicitly programmed. By using this module, You will get the time and date from the timezone that your local computer is present. This module just gets the date and time from the host computer ( Which in this case, it is your computer from which the program is executed ).
Before diving into in-depth functions. Let’s start with a simple program that returns today’s date using the date object in the datetime module.
Example: Get current date
Today’s date: 2021-09-28
today() method will give you the present date of your timezone. If you need just the year or month or day then you can use this method with the respective keywords.
Example: Getting date attribute wise
Present Year:2021 Present Month:9 Present Date:28
Example: Program to count the number of days from the present date to a specific day
Number of days left till graduation: 682 days, 0:00:00
This method is similar to the date method but this is an upgraded version of the date object which will get you both the date and time from your local system. Let’s write the same program, which we wrote for the date object but this time to calculate the remaining days with time.
Example: Program to count remaining days
Time left till the graduation: 681 days, 22:12:03.851113
This object allows us to add or subtract time or date to a specific date and time.
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Example: Adding and subtracting time
The date after adding 9 hours: 2021-09-28 10:49:39.577570
The date after adding 1 day: 2021-09-29 01:49:39.577570
Parsing and formatting
If we want to convert the dates into readable strings, strftime() method is used.
- format – This is of string type. i.e. the directives can be embedded in the format string.
- t – the time to be formatted.
Example: Converting date to string
12:30:30 September 10 2021
Parsing is used to convert a string into datetime format. strptime() is used to perform this. The parameters are date_string and format respectively.
Example: Convert datetime to string