Python

Python Date and Time Module

In this article, we are going to discuss the Python Date and Time module. Python does not have its data type to represent a date, but it allows the programmer to import a DateTime module. In addition to the date, time can also be displayed by Python in various ways. With the assistance of date and time modules, it is possible to set the Python time and date.

Content of Date Time Module

The data and time can be used in Python by importing the DateTime module. We can import the DateTime module by simply using the import statement as follows:

import datetime

Once the datetime module is imported, we can use the classes, methods, and constants available in the datetime module.

With the dir() function, we can get a list that comprises attributes of the datetime module.

print(dir(datetime))

Commonly used classes in the DateTime module:

Python language uses different types of date, time, and DateTime classes for different functions for representing the date, time, and time intervals.

Here are the commonly used classes in the datetime module:

date Class: This class is used to manipulate the form of the month, year, and day.

time Class: Time does not depend on the day and is represented in an hour, minute, second, and microsecond.

dateTime Class: This is a combination of both classes’ date and time. Therefore it is represented in the form of the month, day, year, hour, minute, second, and microsecond.

timedelta Class: Timedelta class is used to calculate the duration, which shows the differences between two dates, time, and DateTime. The differences can be obtained in microsecond resolution.

How to get the current date and time?

Now, let’s look into a simple example to get the current date and time in python.

import datetime
datetime_object = datetime.datetime.now()
print(datetime_object)

First, we import the datetime module by using the import statement and then creating the datetime object. The datetime objects can be used in Python to check the current date and time, representing today’s date and the current time in the form of year, month, days, hours, minutes, and seconds. After executing this code, the present date and time will be displayed as the output.

How to get the current date?

Now, in the following example, we will see how just to get the current date using the datetime module. Let’s look into the following example code:

from datetime import date
CurrentDate= date.today()
print("Today =", CurrentDate)

We have imported the date from the datetime module and then created an object, i.e., CurrentDate, and printed the CurrentDate.

How to get the current time?

In the previous example, we have seen how to get the current date. In this example, we will see how to get the current time.

import time
localtime = time.localtime(time.time())
print("Local current time :", localtime)

It is the best way to translate the instant time, which is based on seconds. The epoch floating-point value needs to be converted into the time tuple, bypassing through floating-point value to a function which is known as local time, and as you return, the time table will be got with valid 9 items. This is not the formatted one; to get the formatted time, asctime() can be used.

How to get the date from the timestamp?

The timestamp is considered as a database where the date and time can be stored; it can also store the datetime object.

from datetime import date
timestamp = date.fromtimestamp(1611474364)
print("Date =", timestamp)

To get the current date and time, it is possible to create a date object from the timestamp. A UNIX timestamp consists of a number of seconds between a specific date and January 1, 1970, at UTC. It is possible to convert timestamp to date by using the method fromtimestamp().

Calculate the difference between two date and times

Now, let’s look into an example to determine the difference between the two dates and times.

import datetime
from datetime import timedelta

my_datetimeFormat = '%Y-%m-%d %H:%M:%S.%f'
my_d1 = '2019-02-25 4:01:29.442'
my_d2 = '2021-01-24 08:36:49.047'
my_diff = datetime.datetime.strptime(my_d1, my_datetimeFormat) \
           - datetime.datetime.strptime(my_d2, my_datetimeFormat)

print("Difference:", my_diff)
print("Days:", my_diff.days)
print("Microseconds:", my_diff.microseconds)
print("Seconds:", my_diff.seconds)

In terms of finding out the differences between two dates with python’s help, the user can use the timedelta class. It is available in the datetime library. This class accumulates the differences between the two dates. The differences between two dates can find out by two different date objects. In this case, let’s suppose two date objects are date 1 and date 2. The difference between two date objects can be represented in the form of minutes and the seconds of the timedelta object.

Format Date Time using strftime()

We can format date and time using the strftime() method. Here is an example:

import datetime

z = datetime.datetime(2021, 1, 24)

print("Fullname of Month: ",z.strftime("%B"))
print("Short Name of Month: ", z.strftime("%b"))
print("Numeric value of Month: ", z.strftime("%m"))

print("\nDay: ", z.strftime("%d"))
print("Week Day: ", z.strftime("%A"))
print("Week Day: ", z.strftime("%a"))

The purpose of using a date-time object is to convert data objects into readable strings by using a particular method. This method is known as strftime(). It needs one parameter and format for formatting the returned string.

Conclusion

The datetime module is a very helpful module in python to manipulate date, time. In this article, we have discussed the commonly used classes, objects, methods. We have also looked into several examples and the outputs to understand the basic concept of the datetime module.

About the author

Sukumar Paul

Sukumar Paul

I am a passionate software engineer and blogger. I have done my Masters in Software Engineering from BITS PILANI University, India. I have very good experience in real-time software development and testing using C, C++, and Python. Follow me at thecloudstrap.com.