In this tutorial we will learn about Python time. Python Variable is discussed in our previous tutorial. Python Time is helpful when your work needs synchronization with system time.
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 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.
Copy# 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 print(currentTime,'\n') # 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.
Copyprint('Python Time Formatted is :', time.strftime("%d/%m/%Y", currentTime))
The output produced will be like below.
CopyPython Time Formatted is : 23/08/2017
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 calendar module.
Copy# import the module import calendar # print the current month print('The month of August is:\n', calendar.month(2018, 8)) # set first day of week as sunday calendar.setfirstweekday(6) # 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
CopyThe 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,
dateutil module. If you get some time, consider reading Pythons Official Reference for more information.
So, that’s all for this tutorial. Hope that you will read more and gain knowledge more on Python time. Any further query? Please use the comment box below.