How to Use Python’s time Module

How to Use Python’s time Module

Originally posted on makeuseof.

Time and date manipulation is one of the more complicated coding tasks. Fortunately, Python makes it much easier with its powerful time module.

Python’s time module offers a wide variety of time-related features and is often handy when building your backend with Python. Using this library, you can fetch the current time and date in standard formats. You can calculate time differences and schedule time-specific operations in your code.

With practical examples, let’s take you through some of the most useful ways to use the time library.

Getting Started With the time Library

The time module is one of the most intriguing treasures in Python’s versatile library repository. It’s built into Python, so you don’t need to install it separately. You just need to import it into your code to start using it.

Although Python’s time library has many methods, and it may seem overwhelming at first, we’ll focus on the ones you’re likely to use most often.

To start using the time module, import it in your script with the following statement:

import time

Get the Default Epoch

The epoch signature of the time library starts on the first day and hour of 1970 on Unix systems by default. This is platform-dependent, though. So the epoch or starting time and date may be different, depending on the operating system you’re using.

To view the default epoch on your OS:

import time
default_base = time.gmtime(0)
print(default_base)
 
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, 
                 tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, 
                 tm_yday=1, tm_isdst=0)

The above tuple output (an object of type time.struct_time) contains the time structure of the time module. It’s where the library stores date and time details by default. From the result, tm_year dates back to 1970, with some other properties having zero as their default value. By the way, gmtime returns the Greenwich Mean Time which may be different from your local time zone.

You can get the local epoch using time.localtime() instead:

import time
default_base = time.localtime(0)
print(default_base)

Running the above code may change the values of individual properties, depending on your local time zone. For example, during British Summer Time in the UK, tm_hour will be “1” instead of GMT’s “0”.

See the Current Time and Date Detail

To get the current time as a time.struct_time object, call time.gmtime() without any arguments:

import time
current_time = time.gmtime()
print(current_time)
 
time.struct_time(tm_year=2021, tm_mon=10, tm_mday=2, 
                 tm_hour=11, tm_min=13, tm_sec=18, tm_wday=5, 
                 tm_yday=275, tm_isdst=0)

As you did in the previous examples, replace time.gmtime() with time.localtime() to see your current local time.

Calculate the Time Between the Epoch and the Current Time

Use the time.time() function to see the number of seconds between the current time and the epoch:

import time
print("Time difference in seconds:", time.time())
 
Time difference in seconds: 1633178361.142249

To see the year difference:

import time
 
# Calculate the number of years: 
print("Year difference is approximately:", round(time.time() / (3600 * 365 * 24)), "years")
 
Year difference is approximately: 52 years

Extract the Current Local Time

It’s not often necessary in practice, but you can access each of the values in a time.struct_time object by accessing its properties directly.

For example, to get the current hour, minute, and year from your current local time:

import time
 
current_local_time = time.localtime()
 
hours = current_local_time.tm_hour
mins = current_local_time.tm_min
year = current_local_time.tm_year
 
print(("The local time and year detail are: {}th hour, {}mins, and year {}").format(hours, mins, year))
 
The local time and year detail are: 11th hour, 49mins, and year 2021

To automate the output instead of hardcoding it as we did above, you can output the current local time using the time.ctime() function.

Here’s how to see the current local time using time.ctime():

import time
print(time.ctime())
 
Sat Oct  2 13:58:07 2021

But the above option doesn’t give you any control over the output.

To manipulate the output, you can stringify the time format using time.strftime() with string annotations:

import time
current_local_time = time.localtime()
 
# Get the current local time: 
current_local_time = time.localtime()
 
# Stringify the current local time using string annotations: 
dtime = time.strftime("The date and time is: %a, %d-%b-%Y, %I:%M %p", current_local_time)
 
print(dtime)
 
The date and time is: Sat, 02-Oct-2021, 11:57 AM

In the above code, %a represents the abbreviated current day name. The %p represents morning or afternoon, in your locale. In English, this translates to either AM or PM.

You can take a look at all possible string annotations for strftime() in the Python docs in your free time. Feel free to tweak them as you like, to format a time to your specific requirements. You can experiment by adding more string options to the above example and seeing what they output. For instance, you can replace %I with %H to get a 24-hour format of the current time instead.

Schedule Code With Python’s time Module

You can delay code execution using the time.sleep() function. This function can be helpful when you need to schedule requests or run a multithreaded program using Python.

Let’s see how it works:

import time
time.sleep(3)
print("This post will show after 3 seconds")

Note that time.sleep() only accepts float and integer arguments, which it translates to seconds. So if you’re scheduling for the next hour or minute, you’ll need to convert these to seconds.

To delay the output by an hour, for instance:

time.sleep(3600)
print("This post will show after an hour")

Create a Countdown Timer Using time.sleep()

Using the time.sleep() function and Python’s for loop, let’s create a countdown timer that accepts a user’s input:

import time
print("Start counting seconds from:")
 
# Create a timer input field that accepts an integer  
timer = int(input())
 
# Increment the timer so that it starts at the specified input  
timer = range(timer + 1)
 
# Assign the length of the timer to a new variable =>
# Then remove one from timer's length to match its index  
v = len(timer) - 1
 
for i in timer:
    # Increment the time every one second 
    time.sleep(1)
 
    # Concatenate the previous count with the next count 
    # to prevent new line at each iteration 
    print(timer[v], end = " ", flush=True)
    print("", end = "", flush=True)
 
    # Decrease the length of timer input by one for each iteration 
    v -= 1

When you run the above code and set your time value, it decreases the specified value every second until it reaches zero.

Make Proper Use of Python’s time Library

You now know how to access the current time from your Python code and manipulate time and date output. The time module is also a valuable tool for tracking requests on the server end when you’re using Python for backend programming.

And because the outputs are mostly integers or floats, you can operate on them as you like to get your time in hours, days, months, or years.

 

Source: makeuesof