Nuts and Bolts of datetime module in Python

Karthikeya Sankaramanchi
7 min readFeb 20, 2021

Working with date and time in python is very crucial while web development or when dealing with time series data. so having practical knowledge on working with date and time in python is a big asset..

In this article, I will take you to the basic implementation of date and time in python by using datetime module available in core python. So without any further due let’s get started….

First things first, We need to import datetime module available in python as shown below. After that we will look into how to work with date object, then time object and at last we will see how to work with both at the same time.

importing datetime module

This line imports all the pre-defined classes available under datetime module. Let’s have a look into date class available in datetime module to work with date objects.

date constructor method will take three items as a parameter. Year, Month and day and construct a date object for us as shown below.

Created a date object using date() method available under datetime module

The year, month and day that we provided to date class need not be current system date. We can initiate date class with any year ,month and year so that date class will create date object for us with given information. Now suppose if we want to create a date object based on your current system’s date.

If above terminology like class , constructor confuse you, Just have a look on comments in below code to understand a typical class, constructor structure in python. I hope you have now clear idea about date class implementation in datetime module after looking into below code.

A Basic class Implementation in Python
Output of above code

Let’s get back to date class again. If we want to create a date object based on current system date. date class has a useful method called today() which returns the current system date as date object as shown below

today()

Every class in a python either it is pre-defined class like date in our case or any user-defined class will contain both methods as well as properties. There are three such properties available under pre-defined date class, Those are day , year and month. Suppose you have already got a date object, Now if you want to get only year part or only month part or only day part from that object in that case those properties will be very useful as shown below

Useful properties available in date class

There is another useful method available under date class, That is weekday() which tells us about the day name of a given date object. This method returns a number between 0 to 6 where each digit represent a day. In this case 0 represents Monday(1- Tuesday, 2-Wednesday, 3-Thursday, 4-Friday, 5-Saturday and 6-Sunday). It is as shown below

5 means Saturday

Now we will have a look on how to work with time in python using time class available under datetime module. As same as date class, We need to create time object by initializing time class Constructor method by providing three parameters Hours , Minutes , Seconds and Microseconds as shown below

time(hours,minutes,seconds,microseconds) available under time class

As seen in date class, In time class we have some properties to get the individual parts from the time object as shown below

It’s not always guaranteed that the data we are working will have both date and time separately. Sometimes it is needed to work with both date and time at a time. Suppose if we want log some details into a file for every one hour along with date then datetime class which is available under datetime module will shine. Don’t be confused with the names here, datetime is module consists of three classes. One is date to work with dates, time class to work with time and datetime to work with both date and time as shown.

As same as date and time class, We need to create datetime object by initiating constructor method of datetime class with Year, Month, Day, Hours, Minutes, Seconds and Microseconds parameters as shown.

datetime(year,month,day,hours,minutes,seconds,microseconds)

There are two useful methods in datetime class, One is date() method which takes datetime object as parameter and returns only date part of provided object so that we can work with returned date object as discussed above. Another method is time() which takes datetime object as parameter and returns only time part of provided object so that we can work with returned time object as discussed above.

There are another two useful methods available under datetime class. One is today() which returns the current System’s date and time. Another method is now() which also returns the current System’s date and time. However, we can pass a additional parameter tz which refers to the time zone for which we need current date and time. By default tz is None, So both today() and now() will produce the same results as shown below. We will discuss more on time zones later.

Next most useful topic we are going to cover in datetime module is working with timedelta. timedelta Objects are used to calculate difference between dates and time. Suppose I have a date object with me and i need to calculate what is the exact date after a few days or i need to get what is the exact time after a few hours from a given time object.

In order to work with timedelta, First we need to create a object to timedelta class. So to create an object for timedelta class, We need to initiate timedelta class constructor with few parameters like days, weeks, seconds, microseconds, minutes, hours. Depending upon the difference we are finding out we can provide those parameters. Let’s see days parameter in action

In line number 5 of above code, We only created date object as i am showing example for only days parameter in timedelta class. If we want to work with both date and time then we need to create datetime object so that we can work with time related parameters in timedelta class. Let’s see this in action. Suppose i want date and time after 365 days, 2 weeks , 4 hours and 54 minutes. To achieve these kind of problems we need to pass other parameters to timedelta class.

Here we created a datetime object so that we can calculate both date and time difference

As of now, Using timedelta objects we are able to calculate date or time difference between given datetime object. So Is there any way to calculate the difference between two dates or time?. and answer is YES. Just by adding or subtracting two date or time or datetime objects we will be able to calculating the difference between them.

Difference Between date objects and datetime objects

There is one most useful methods available under date, time and datetime class are strftime() . strftime(format) will take user defined format as parameter and change date ,time or datetime object into that format. Suppose i want my datetime object to print like for example “January-01–2021,4:52-PM” in this format. Let’s see in action.

strftime(format)

If we see the above code, We provided some weird format string as a parameter to strftime() method. Here %B means i want my month to be printed as full month name. %d means i want my month number to be printed as two digit number and so on. Every Format code has a special meaning here. So how to remember these special characters?. There is no need to remember these things. Attaching a link for your reference to these format codes.

There is another method which is available only under datetime class is strptime() method, We have strptime(string, format) method which takes a string and convert it into datetime object. So how python able to convert it?. For that purpose we are providing format parameter means we are telling explicitly that the string i passed as parameter is in this format. So Please convert it into datetime Object. Again please refer to above attached link to know about the format codes.

This is for this article. The only thing we are missing is dealing with different time zones which is very important. I will be doing that part alone in upcoming blogs. Hope this article helps!!

--

--