Python provides a module named datetime to work with the date and time. Sometimes in the real life application development, we need to work with the date and time. The date is not a separate data type in Python, but we can work with the date objects by importing the module named with datetime, time, and calendar.

The datetime module permits us to generate the custom date objects to perform various operations on dates like the comparison, formatting, etc.

To work with dates as date objects, we need to import datetime module into the Python source code.

 Get the current time

The date module provides the localtime() function which is used to get the current time tuple. The example is following:

Output:

The time() function

The time() function returns the total number of tick spent since 12 AM, 1st January. A tick can be considered as the smallest unit of the time. The time instants are counted since 12AM, 1st January.

Output:

Time Tuple

Index Attribute Values
0 Year 4 digit
1 Month 1 to 12
2 Day 1 to 31
3 Hour 0 to 23
4 Minute 0 to 59
5 Second 0 to 60
6 Day of weak 0 to 6
7 Day of year 1 to 366
8 Daylight savings -1,0,1, or -1

Get formatted time

The time module provides the asctime() function, which is used to format the time. It returns the formatted time for the time tuple which is passed in the asctime().

Output:

Sleep time

The sleep() method is used to stop the execution of the python script for a  given amount of time. Consider the following example:

Output:

Create date object

The date objects can be created by using datetime constructor and by passing the desire data for which the date objects are to be created. Consider the following example:

Output

Get current date and time

The now() returns the current date and time. Let’s consider the following example:

Output:

Inside datetime

Using dir() function to get a list containing all attributes of a module.

Output:

Get current date

Output:

In the above program, we have used today() method to define the date class to get a date object containing the current local date.

Comparison of two dates

The two dates can be compared by using comparison operator like >>=, < and <=. Consider the following example.

Output

Difference between two dates and time

Output:

The calendar module

Python provides a calendar object that contains various method to work with the calenders.

The above code will generate the calendar of the year 2017 month of November

Output

python-date-and-time

Printing the calendar of the whole year

Output

python-date-and-time-1

Pin It on Pinterest

Share This