Python time Module With Examples

In this tutorial, we will learn about the Python time module. Python Variable is discussed in our previous tutorial. Python time module is helpful when your work needs synchronization with system time.

Python time Module

When you work for a real time project, you may need to synchronize your task with system time. For example, when it’s 8 o’clock, your program should send a message to a group of people. For that purpose, you should know how to get system time using python code.

To do so, you need to import Python time module. To get the current time we need to use localtime() function from the time module. The function gets input from time() function. The following code will help you to print current time in python.

# import the module
import time
# get the current clock ticks from the time() function
seconds = time.time()
currentTime = time.localtime(seconds)
# print the currentTime variable to know about it
# use current time to show current time in formatted string
print('Current System time is :', time.asctime(currentTime))

And your output will be similar to this


Python time format

We can use strftime function to format the time.

print('Python Time Formatted is :', time.strftime("%d/%m/%Y", currentTime))

The output produced will be like below.

Python Time Formatted is : 23/08/2017

Calendar Module

In the previous section, we talked about Python’s time module. We can get current time using python time module and then format it as we require.

In this section, we will use Python’s calendar module to get information about calendars. The following example code will show us some functions of the calendar module.

# import the module
import calendar
# print the current month
print('The month of August is:n', calendar.month(2018, 8))
# set the first day of the week as sunday
# re print the calender
print('The month of August is:n', calendar.month(2018, 8))
# print if a year is leap year
print('Is 2017 a leap year? Ans:', calendar.isleap(2017))
print('Is 2016 a leap year? Ans:', calendar.isleap(2016))

The output of the following code will be

The month of August is:
     August 2018
Mo Tu We Th Fr Sa Su
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
The month of August is:
     August 2018
Su Mo Tu We Th Fr Sa
          1  2  3  4
 5  6  7  8  9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
Is 2017 a leap year? Ans: False
Is 2016 a leap year? Ans: True

There are other modules other than time and calendar. For example, datetime module, dateutil module.

If you get some time, consider reading Pythons Official Reference for more information.

By admin

Leave a Reply

%d bloggers like this: