Working with Python Datetime Module

Working with Python Datetime Module

10 mins read955 Views Comment
Updated on Nov 1, 2022 14:52 IST

The Python datetime module supplies classes to manipulate times and dates. It is categorized into date, datetime, time, timedelta, tzinfo and timezone.

2022_08_MicrosoftTeams-image-10.jpg

Author: Nishi Paul

Table of Contents

What is the Python Datetime Module?

Datetime module of Python

Python does not have any date data types of its own, just like it has int, float, etc. data types. However, Python has a whole module dedicated to date and time, known as datetime, to work with date data types. Before getting started with date data types in Python, import the datetime module.

import datetime

Now this datetime module has got several in-built functions to use. This makes our life a lot easier. We have to think about when and where to use specific functions from this library.  So, let us explore all the functions one by one.

Explore free Python courses

To Display the Current Date and Time

We use the function of datetime.now() to display the current date and time. You will get the current date and time of the system you will use.

 
<em>current_date_time = datetime.datetime.now()
print(‘Current Date and Time is – ‘, current_date_time)</em>
Copy code

Output –

 
Current Date and Time is2022-07-20 10:44:28.315804)
Copy code

Just as in my system, the date is 20 July 2022 (given in year-month-date format), and the time is 10:44:28, and 315804 are microseconds. So it displays the output of the year, month, day, hour, minutes, seconds, and microseconds.

To Display Parts of the Date Individually

Now, what if you want to get the year, month, day, etc. that is all the parts of the date individually? In that case, you need to do the following –

 
<em>print(‘Year is – ‘,current_date_time.year)
print(‘Month is – ‘,current_date_time.month)
print(‘Day is – ‘,current_date_time.day)
print(‘Hour is – ‘,current_date_time.hour)
print(‘Minute is – ‘,current_date_time.minute)
print(‘Second is – ‘,current_date_time.second)
print(‘Microsecond is – ‘,current_date_time.microsecond)</em>
Copy code

Output –

 
Year is2022
Month is7
Day is20
Hour is10
Minute is44
Second is47
Microsecond is590848
Copy code

So the current_date_time is your datetime object, which stores the current date and time as per your system. Then you are taking the individual values out of your current datetime object as above.

Free QR Code Generator using Python
Free QR Code Generator using Python
Do you want to know QR code is generated? Then read this blog which tell you how to implement this using python. Do you want to know QR code is...read more
Pattern Programs in Python
Pattern Programs in Python
Do you want to learn how to make different patterns in python.Here in this article you will find 20 python programs for different pyramid patterns. This article implemented different Pattern...read more
Type Conversion in Python: Types and Examples
Type Conversion in Python: Types and Examples
Type conversion in Python refers to the direct conversion of object of one data type to another data type. In this conversion, Python interpreter automatically performs conversion. Type conversion in...read more

To Display the Current Date and Time in the Specified Format

Now, if we want to get the data output in an easy-to-read form, then we use the strftime() function. If we wish to print the date in the format of day/month/year, then we have to pass the similar form inside the strftime() function as follows –

 
<em>print(‘Date in the Indian format of day/month/week is – ‘, current_date_time.strftime(%d/%m/%y))</em>
Copy code

Output –

 
Date in the Indian format of day/month/week is20/07/22
Copy code

So, %d is giving the day number of the month, %m is giving the month number of the year, and %y is giving the year in short. If we want the year in the form of 2022, then we have to use %Y (capital Y).

Now, if we need only the date of today in our required form then we can do this –

 
<em>current_date = datetime.date.today()
print(‘Today’s date is – ‘, current_date.strftime(%d/%m/%Y’))</em>
Copy code

Output –

 
Today’s date is03/08/2022
Copy code

date.today() is giving only the date of the system.

For another example, let’s say we want to get the day name, and month number from the date, then we can do the following –

 
<em>print(‘Today is– ‘, current_date_time.strftime(%A),and this is, str(current_date_time.strftime(%W’)), ‘th week of the year’)</em>
Copy code

Output –

 
Today is– Wednesday and this is 31st week of the year)
Copy code

So, as you might have guessed %A is giving the day name, and %W is giving the week number when the week starts from Monday.

There are several other formats to use inside the strftime(), and the above ones are the most common ones. We do not generally remember all the forms, so we take the help of documentation while looking for the needed formats.

To Instantiate a Given Date

Suppose the date of 16 September 2021 is given, then how can you instantiate it? Well, by doing the following –

 
<em>another_day = datetime.date(2022, 9, 16)
#with format
print('Date instantiated is - ', another_day.strftime('%d/%m/%Y'))
#without formatting
print('Date instantiated is - ', another_day)</em>
Copy code

Output –

 
Date instantiated is - 16/09/2022
Date instantiated is - 2022-09-16
Copy code

So you need to write the date inside the datetime.date() in the form of year, month, and date. Then as you can see, we can get the instantiated data in any way we want.

To Instantiate the Required Time

Suppose I want to instantiate 8 hours, 40 minutes, and 20 seconds. Then we will do the following –

 
<em>time_instantiated = datetime.time(8, 40, 20)
#with format
print('Time is - ', time_instantiated.strftime('%H-%M-%S'))
#without format
print('Time is - ', time_instantiated)
#we can also instantiate time with microseconds and then print it
time_with_micro = datetime.time(9, 30, 43, 23674)
print('Time with microseconds is - ', time_with_micro)</em>
Copy code

Output –

 
Time is - 08-40-20
Time is - 08:40:20
Time with microseconds is - 09:30:43.023674
Copy code

So as you can see, we can instantiate the time using the time() function and then print it in any way we want. Also, we can give microseconds too.

To Instantiate Both Date and Time

We have instantiated the date and instantiated time separately. Now we will instantiate the date and time together, and it will look the same as we have seen it at the start for the code datetime.datetime.now(). Let’s see how to do it –

 
<em>date_one = datetime.datetime(2022, 6, 20, 12, 30, 50, 38928)
print('Instantiated date and time is - ', date_one)</em>
Copy code

Output –

 
Instantiated date and time is - 2022-06-20 12:30:50.038928
Copy code

Here we have instantiated the date of 20 June 2022 and time of 12 hours 30 minutes 50 seconds.

Finding the Difference in Both Dates and Times

Well, now we know how to instantiate dates and get the current date. We can find the difference between the two dates now. Let’s see how we can do that –

 
<em>date_one = datetime.datetime(2022, 6, 20, 12, 30, 50, 38928)
current_date = datetime.datetime.now()
print('Current date and time is - ', current_date)
print('Instantiated date and time is - ', date_one)
difference = current_date - date_one
print('Difference in the date and time is - ', difference)</em>
Copy code

Output –

 
Current date and time is - 2022-07-20 11:40:31.260332
Instantiated date and time is - 2022-06-20 12:30:50.038928
Difference in the date and time is - 29 days, 23:09:41.221404
Copy code

As you can guess, we need to subtract the two dates. Congratulations! You now know how to find the difference between two dates and times.

Similarly, you can get the difference between only the dates as follows –

 
<em>date_one = datetime.datetime(2022, 6, 20, 12, 30, 50, 38928).date()
current_date = datetime.datetime.now().date()
print('Current date - ', current_date)
print('Instantiated date - ', date_one)
difference = current_date - date_one
print('Difference in the date ', difference)</em>
Copy code

Output –

 
Current date - 2022-07-20
Instantiated date - 2022-06-20
Difference in the date: 30 days, 0:00:00
Copy code

Here we have subtracted the past time from the present time,i.e., 20 June from 20 July. As 20 June comes before 20 July, the subtraction gave us a positive number of 30, which is the difference in days between the two dates. Now, if we do the reverse, i.e., by subtracting 20 July from 20 June, we will get the difference of dates in negative. In this case, we have to use the absolute function (that is abs()) to get the absolute value. Let’s see it in code –

 
<em>date_one = datetime.datetime(2022, 6, 20, 12, 30, 50, 38928).date()
current_date = datetime.datetime.now().date()
print('Current date - ', current_date)
print('Instantiated date - ', date_one)
difference = date_one - current_date
print('Difference in the date without absolute : ', difference)
print('Difference in the date with absolute : ', abs(difference))</em>
Copy code

Output –

 
Current date - 2022-07-20
Instantiated date - 2022-06-20
Difference in the date without absolute : -30 days, 0:00:00
Difference in the date with absolute : 30 days, 0:00:00
Copy code

How to Get the Date From A String Type

If the date provided is in the form of a string, then we need to use the function of datetime.strptime() from the module datetime. This will map the date, month, and year in the datetime format from the input string type date, and then we can use the converted datetime for calculating the difference in the dates. Let’s see this in code –

 
<em>date_june = '20 June, 2021'
date_june_converted = datetime.datetime.strptime(date_june, '%d %B, %Y')
print('Date from the String format of date is - ', date_june_converted)</em>
Copy code

Output –

 
Date from the String format of date is - 2021-06-20 00:00:00
Copy code

Now the format specifiers inside the strptime() hold the same meaning as in the strftime(). %d is for mapping the day, %B is for mapping the month, and %Y is for mapping the year. Now, if someone provides the date in the string format but writes it in this way – 25 Dec, 20, then what shall we do? Let’s see –

 
<em>date_june = '25 Dec, 20'
date_june_converted = datetime.datetime.strptime(date_june, '%d %b, %y')
print('Date from the String format of date is - ', date_june_converted)</em>
Copy code

Output –

 
Date from the String format of date is - 2020-12-25 00:00:00
Copy code

As you can see, you need to specify the format accordingly for mapping the date, month, and year as given. If I were to use %B in place of %b, I would have gotten a value error as %B can understand the full month name of December and not Dec, whereas %b can understand Dec and not December.

So these are the things that we should keep in mind while working with date time. These are the important things to remember about dates while working. Before wrapping up, let’s see a use case of this datetime module to get a clear insight.

Explore Free Online Courses with Certificates

Datetime Module – A Real-life Case Study

Use Case

Problem Statement – Suppose we have 26 persons, named from A to Z, and these 26 persons enrolled with us on 26 different dates. So, we will make two lists of the names of these 26 persons and the dates. We will then make a dictionary using these two lists. So, each person will have a date by the side of his or her name. So the name will be the key, and the dates will be the value of the dictionary. We aim to find out the number of persons enrolled in the given date range. Let us see how we have done it.

Suggested approach – You might have noticed that while creating a list for dates, I used the function of timedelta, which is in the datetime library. This timedelta function takes the parameter of days, i.e., timedelta(days = values). So you may write days or you may not, it does not matter. Whatever value you give inside the timedelta function, that value will be the number of days. Now you can subtract or add any number for days with the given date using timedelta. For example, if today is 20 July, 2022, then if I do today + datetime.timedelta(2), then I will get the output of 22 July, 2022, as I have added two days with the current date.

Similarly, in the below code, I have subtracted one day from each current date and stored it in the list called dates. You can write the print function inside the for loop to see the output at each iteration.

Now, after creating the dictionary of names and dates, I have externally provided the start date and the end date. We will find out all the names between these start and end date. For this, I have used a for loop, iterating the dictionary to filter the names for which the date is between the start and end dates. I have used a counter to count the number of names within the given date range. Again, you can use print functions inside the loop to see the output at each iteration.

 
<em>import datetime
names = []
dates = []
#initializing names of A, B, C .... upto Z
for i in range(65,91):
names.append(chr(i))
#intializing 26 dates starting from today and going back to 26 days
date = datetime.date.today()
for i in range(26):
dates.append(date.strftime('%d-%m-%Y'))
date = date - datetime.timedelta(1)
#creating a dictionary by zipping all the names and dates
names_dates = dict(zip(names, dates))
#finding out how many names are present between 29 June to 14 July
count = 0
name_in_this = []
start_date = '29-06-2022'
end_date = '14-07-2022'
for i in (names_dates.items()):
if i[1] start_date:
name_in_this.append(i[0])
count = count + 1
print('Number of names in this date range is - ',count)
print('Names are - ', name_in_this, end = ' ')</em>
Copy code

Output –

 
Number of names in this date range is- 14
Names are- ['H', 'I', 'J','K','L','M','N','O','P','Q','R','S','T','U']
Copy code

Hence, you can see how we are using dates to filter out data. This date time module is widely used for analysis and with other Python frameworks like pandas.

Do check out working with Date and Time in Pandas

Why Learning the Datetime Module in Python is Essential?

Date and time are one of the most neglected topics among beginners. They need to understand that while working with real-life data, i.e., while working in a company, date and time will play an essential role. So, knowing the date and time is of utmost importance. Now you may ask about how and where we use it. Before explaining how we use it, I will give you an example of where we use it.

You might know that thousands, even millions, of data are getting generated each day. To work with these data, we need to filter out the data for date and at certain times for time. We might want to know about the data pattern for the last 30 days. As you can guess, we need to filter out the data for only these last 30 days. From this, we get the required data, and the computation or the processing for data filtration is also faster.

Let us take a real-life example. We know that there are millions of users using Paytm. Now, let us assume that we have transaction data of an active user A, using Paytm for two years and making a minimum of 2 transactions each day via Paytm. Some days, user A will make more than two transactions. Hence, user A will make a minimum of 1460 transactions in 2 years.

Now, if we want to see the latest transactions made by user A, then we have to filter the data of user A by date and time. If we need the transactions for the last 30 days, then we will get a minimum of 60 transactions for 30 days. This data is much less than the data we will have for two years if we don’t filter it by date. Hence you can see that filtering by date is helpful in both avoiding unnecessary data and saving computation memory, thereby increasing processing speed.

I hope you got a clear understanding of why we should learn it and use it.

Summary

The datetime module of python is easy and super useful. You can use the datetime module at places where data has to be fetched or grouped as per dates.

The things you can do using the datetime module are –

  • Fetch the required data for a given date range from the database.
  • You can work much faster by taking out a small dataset, making the processing faster.
  • You can segment features as per the date range.
  • You can even do time series analysis using the date range.

There are multiple things to do using the module. You have to think about how to make the best use of it.

_______________

Recently completed any professional course/certification from the market? Tell us what you liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio