Since Python deals with real dates and time, it provides us many modules in which the date & time module is unique. In this way, Python allows us to schedule our program to run at a particular time.
As the date is not a data type, we can work on date objects by importing time, calendar and datetime modules.
There are six types of datetime classes:
date - consists of year, month, and day as attributes.
time - has hour, minute, second, and tzinfo as attributes.
datetime - a group of date and time.
timedelta - shows us the difference between two dates, time and datetime.
tzinfo - gives us the time zone information objects.
timezone - is embedded with Python versions – it’s the class that implements the tzinfo
abstract base class.
time()
time()
is a function of the time module that returns the total number of ticks spent since
import time;print(time.time()) # print the number of ticks spent
Now, the issue is, “how can we get the current local time tuple?”
Before going into the current time tuple, we should take a look into the time tuple.
Every time is treated as a tuple of nine numbers. They are:
Year, Month, Day, Hour, Minute, Second, Day of Week, Day of Year, Daylight savings
Now, to get the current time we have to use a function of time called, localtime()
.
import time;# returns a time tupleprint(time.localtime(time.time()))
Python’s sleep module is a well-known method that is used to stop the execution of a given code for a while. Let’s have a look at a sample program.
import timefor i in range(0,6):print(i*2)# Each element will be printed after 4 secondstime.sleep(4)
datetime
moduleThe Python datetime
module helps us to create new customized date objects that help us to perform operations like comparisons.
However, for these, we have to the import datetime
module into our source code (as shown below).
import datetime# returns the current datetime objectprint(datetime.datetime.now())