Mastering the Python Time Module: A Comprehensive Guide
The time module is a standard module in Python. It’s essential when working with Python to include time-related operations.
The time module provides various time-related functions and methods, which can be accessed by importing the time module:
import time
The time module represents the time in seconds since the epoch unless otherwise specified. This is common for Windows and most UNIX systems, but what is the epoch?
- 1 Understanding Epoch
- 2 Time representation
- 3 Time zones and UTC
- 4 Breaking down the time structure
- 5 Working with daylight savings
-
6
Python Time Module Essential Functions
- 6.1 time() function
- 6.2 ctime() function
- 6.3 asctime() function
- 6.4 sleep() function
- 6.5 gmtime() function
- 6.6 localtime() function
- 6.7 mktime() function
- 6.8 strftime() function
- 6.9 strptime() function
- 6.10 perf_counter() function
- 6.11 perf_counter_ns() function
- 6.12 process_time() function
- 6.13 process_time_ns() function
- 7 Python Time Mastery
- 8 Further Reading
Understanding Epoch
Epoch time, also known as UNIX time, represents the time in seconds that have passed since January 1, 1970, 00:00:00 Coordinated Universal Time (UTC).
This date is referred to as the “epoch” and is a common point where the time starts across many programming languages, including Python.
In Python, the time before the epoch can be represented but is usually expressed in seconds since the epoch. This approach simplifies the calculation and representation of time.
Let’s see an example of getting the current time in seconds since the epoch.
import time current_time = time.time() print(current_time)
Output:
1649268400.23
The time.time() function returns the current time in seconds since the epoch as a floating point number, but is this the only way to represent time using the time module in Python? no.
Time representation
Python’s time module offers various ways to represent time. These include timestamps and struct_time objects (time tuple).
Timestamps
A timestamp is the most common way to represent time, which is expressed in seconds since the epoch.
import time current_timestamp = time.time() print(f"Current timestamp: {current_timestamp}")
Output:
Current timestamp: 1649268400.23
In this example, we use the time.time()
function to get the current time as a timestamp.
Struct_time Objects
The struct_time objects are returned by various functions in the time module, such as gmtime()
, localtime()
, and strptime()
. It is essentially a time tuple with a namedtuple interface.
import time current_time_utc = time.gmtime() print(f"Current UTC time: {current_time_utc}")
Output:
Current UTC time: time.struct_time(tm_year=2023, tm_mon=7, tm_mday=1, tm_hour=8, tm_min=47, tm_sec=30, tm_wday=5, tm_yday=182, tm_isdst=0)
In the above example, time.gmtime()
returns a struct_time
object that represents the current time in UTC.
Time zones and UTC
Time zones are regions of the Earth that have the same standard time.
They follow the concept that the Earth’s 24-hour day is divided into 24 time zones and the time is the same within each of these zones.
Python’s time module does not directly support time zones.
However, it does offer functions to handle daylight saving time, a common aspect related to time zones, and allows conversions between local time and Coordinated Universal Time (UTC).
Time zones are usually defined as offsets from UTC.
For instance, the Central Time Zone in the United States is UTC-6 hours during standard time and UTC-5 hours during daylight saving time.
Understanding time zones is crucial when working with time in Python, especially if your application needs to deal with dates and times across different regions.
For more advanced date and time manipulation, including comprehensive timezone handling, you may want to consider using the datetime and pytz modules.
Breaking down the time structure
The struct_time or time tuple structure is made up of 9 fields, each representing a different component of a date and time.
Let’s break down this structure with an example:
import time current_time = time.localtime() print(f"Current time structure: {current_time}")
Output:
Current time structure: time.struct_time(tm_year=2023, tm_mon=7, tm_mday=1, tm_hour=10, tm_min=47, tm_sec=30, tm_wday=5, tm_yday=182, tm_isdst=1)
In the example above, the time.localtime()
function returns a struct_time
object representing the current local time. This object contains the following elements:
tm_year
: The year, e.g. 2023.tm_mon
: The month of the year, ranging from 1 (January) to 12 (December).tm_mday
: The day of the month, ranging from 1 to 31.tm_hour
: The hour of the day, ranging from 0 to 23.tm_min
: The minute of the hour, ranging from 0 to 59.tm_sec
: The second of the minute, normally ranging from 0 to 59, but can be up to 61 where 60 for leap seconds and 61 is supported for historical reasons.tm_wday
: The day of the week, where Monday is 0 and Sunday is 6.tm_yday
: The day of the year, ranging from 1 to 366.tm_isdst
: A flag indicating whether Daylight Saving Time (DST) is in effect. The value is 1 when DST is in effect, 0 when it’s not, and -1 when it’s unknown.
Working with daylight savings
Daylight Saving Time (DST) is the practice of setting the clock forward by one hour during the warmer part of the year, so that evenings have more daylight and mornings have less.
The Python time module provides the tm_isdst
flag in the struct_time
object that indicates whether DST is in effect.
A value of 0 indicates that DST is not in effect, 1 means that DST is in effect, and -1 means that it is unknown.
This flag is set by functions like localtime()
and gmtime()
when they are called without arguments, and it is used by mktime()
to determine whether DST was in effect at the time specified.
Here’s an example:
import time local_time = time.localtime() print(f"DST flag: {local_time.tm_isdst}")
Output:
DST flag: 1
In this example, we retrieve the current local time using time.localtime()
, and then print the tm_isdst
flag. A result of 1 indicates that DST is currently in effect.
Python Time Module Essential Functions
The Python Time module provides a range of functions that help in executing and managing time-related tasks in your Python programs.
These functions can be used for various purposes, like fetching the current time, converting time between different formats, getting the time in UTC, delaying the execution of the program, and measuring the efficiency of your code.
time() function
The time()
function returns the current time in seconds since the epoch, a floating-point value representing the total number of seconds passed since the epoch.
Here’s an example of how to use it:
import time current_time = time.time() print(f"Current time in seconds since epoch: {current_time}")
Output:
Current time in seconds since epoch: 1649268400.23
In this code snippet, the time.time()
function returns the current time in seconds since the epoch.
This value represents the seconds passed since the epoch. It’s an easy way of tracking time in a format that allows for simple calculations, like computing the difference between two times.
ctime() function
The ctime()
function is used to get a string representation of the current time in the following format: ‘Wed Dec 31 17:46:40 2023’. The string returned represents local time in a readable format.
Let’s see it in action:
import time current_time = time.ctime() print(f"Current time string: {current_time}")
Output:
Current time string: Sat Jul 1 10:47:30 2023
In the above code, time.ctime()
returns a string representing the current time. The string is formatted as follows: Day of the week, Month, Day, Hour:Minute:Second, Year.
asctime() function
The asctime()
function converts a time expressed in seconds since the epoch or a time tuple to a string representing local time.
If no argument is provided, it takes the current time.
Here’s an example of using asctime()
with the current time:
import time current_time = time.asctime() print(f"Current time string: {current_time}")
Output:
Current time string: Sat Jul 1 10:47:30 2023
In this code, time.asctime()
returns a string representing the current time in the format: Day of the week, Month, Day, Hour:Minute:Second, Year.
The asctime()
function can also be used to convert a time tuple to a string:
import time t = (2023, 7, 1, 10, 47, 30, 5, 182, 1) time_string = time.asctime(t) print(f"Time string: {time_string}")
Output:
Time string: Sat Jul 1 10:47:30 2023
In this code, time.asctime()
takes a time tuple and returns a string representing that time. The structure of the tuple is (year, month, day, hour, minute, second, day of the week, day of the year, daylight savings flag).
sleep() function
The sleep()
function is used for pausing the execution of a Python program for a given number of seconds.
Here’s an example of its use:
import time print("Start : %s" % time.ctime()) time.sleep(5) print("End : %s" % time.ctime())
Output:
Start : Sat Jul 1 10:47:30 2023 End : Sat Jul 1 10:47:35 2023
In the above code, we print the current time using time.ctime()
, pause the execution for 5 seconds using time.sleep(5)
, and then print the current time again.
The difference between the two printed times is exactly 5 seconds.
This function is handy in many scenarios, such as when you want to delay the execution of the next line of code, simulate a delay in your program, or create an interval between function calls in a loop.
gmtime() function
The gmtime()
function returns the current time in Coordinated Universal Time (UTC), also known as Greenwich Mean Time (GMT).
This function returns a struct_time
object expressed in seconds since the epoch, where all fields are calculated for UTC.
Here is an example of how you can use the gmtime()
function:
import time current_time_utc = time.gmtime() print(f"Current UTC time: {current_time_utc}")
Output:
Current UTC time: time.struct_time(tm_year=2023, tm_mon=7, tm_mday=1, tm_hour=8, tm_min=47, tm_sec=30, tm_wday=5, tm_yday=182, tm_isdst=0)
In the above code, time.gmtime()
returns a struct_time object in UTC. This output shows the year, month, day, hour, minute, and second, all in UTC.
This time does not consider daylight saving time as tm_isdst
is 0.
The gmtime()
function is useful when you need to work with or display time in UTC, which can be especially helpful for applications with users in different time zones.
localtime() function
The localtime()
function is used to convert a time expressed in seconds since the epoch to a struct_time
in local time.
If no argument is provided, it will return the current local time.
Here’s how you can use the localtime()
function:
import time local_time = time.localtime() print(f"Local current time: {local_time}")
Output:
Local current time: time.struct_time(tm_year=2023, tm_mon=7, tm_mday=1, tm_hour=10, tm_min=47, tm_sec=30, tm_wday=5, tm_yday=182, tm_isdst=1)
In this code snippet, time.localtime()
returns a struct_time object representing the current local time.
This function is useful when you need to get the current time according to the system’s local setting.
mktime() function
The mktime()
function is used to convert a time tuple in local time to seconds since the epoch.
This function takes a time tuple and returns a floating-point number representing seconds passed since the epoch.
Here’s an example of using mktime()
:
import time t = (2023, 7, 1, 10, 47, 30, 5, 182, 1) seconds = time.mktime(t) print(f"Time in seconds since epoch: {seconds}")
Output:
Time in seconds since epoch: 1691083650.0
In the above example, time.mktime()
takes a time tuple and returns the corresponding time in seconds since the epoch.
The mktime()
function is useful when you need to perform calculations or comparisons with other timestamps.
strftime() function
The strftime()
function converts a time tuple to a string according to a specific format.
The format is defined by a format string, where different format codes represent different parts of the date and time.
Here’s how you can use the strftime()
function:
import time t = time.localtime() formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", t) print(f"Formatted time: {formatted_time}")
Output:
Formatted time: 2023-07-01 10:47:30
In the code above, time.strftime()
takes two arguments: a format string and a time tuple.
The format string contains format codes, which are placeholders for parts of the date and time.
In this case, “%Y-%m-%d %H:%M:%S” represents year-month-day hour:minute:second.
The strftime()
function formats time as a string, based on a set of format codes.
Here is a table of some common format codes used with strftime()
:
Directive | Meaning |
---|---|
%a |
Weekday as locale’s abbreviated name. |
%A |
Weekday as locale’s full name. |
%w |
Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. |
%d |
Day of the month as a zero-padded decimal number. |
%b |
Month as locale’s abbreviated name. |
%B |
Month as locale’s full name. |
%m |
Month as a zero-padded decimal number. |
%y |
Year without century as a zero-padded decimal number. |
%Y |
Year with century as a decimal number. |
%H |
Hour (24-hour clock) as a zero-padded decimal number. |
%I |
Hour (12-hour clock) as a zero-padded decimal number. |
%p |
Locale’s equivalent of either AM or PM. |
%M |
Minute as a zero-padded decimal number. |
%S |
Second as a zero-padded decimal number. |
%f |
Microsecond as a decimal number, zero-padded on the left. |
%z |
UTC offset in the form +HHMM or -HHMM. |
%Z |
Time zone name. |
%j |
Day of the year as a zero-padded decimal number. |
%U |
Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. |
%W |
Week number of the year (Monday as the first day of the week) as a zero padded decimal number. |
strptime() function
The strptime()
function converts a string representing a time according to a specific format into a struct_time
.
The time string needs to be in the format defined by a format code.
Here’s an example of how to use the strptime()
function:
import time time_string = "2023-07-01 10:47:30" t = time.strptime(time_string, "%Y-%m-%d %H:%M:%S") print(f"Time tuple: {t}")
Output:
Time tuple: time.struct_time(tm_year=2023, tm_mon=7, tm_mday=1, tm_hour=10, tm_min=47, tm_sec=30, tm_wday=5, tm_yday=182, tm_isdst=-1)
In this example, time.strptime()
converts a time string into a struct_time
, based on the format code given.
The time string “2023-07-01 10:47:30” corresponds to the format code “%Y-%m-%d %H:%M:%S” which represents year-month-day hour:minute:second.
Note that the strptime()
function accepts the same format directives as the strftime()
function.
perf_counter() function
The perf_counter()
function provides the current value of the performance counter, a clock with the highest available resolution to measure a short duration.
It does include time elapsed during sleep and is system-wide.
Let’s consider an example where perf_counter()
can be used to calculate the time taken to execute a piece of code:
import time start_time = time.perf_counter() # code execution for i in range(1000000): pass end_time = time.perf_counter() elapsed_time = end_time - start_time print(f"Elapsed time: {elapsed_time} seconds")
Output:
Elapsed time: 0.07634560000003452 seconds
In this example, time.perf_counter()
is used before and after the execution of a for-loop.
The perf_counter measures the elapsed time as the difference between the end time and the start time including the waiting time such as delay or I/O waiting.
The exact time output may vary based on the system’s performance.
perf_counter_ns() function
For higher precision, you can use perf_counter_ns()
which behaves similarly to perf_counter()
, but it returns the time as an integer number of nanoseconds.
import time start_perf = time.perf_counter_ns() for i in range(1000000): pass end_perf = time.perf_counter_ns() elapsed_time = end_perf - start_perf print(f"Elapsed time using perf_counter_ns: {end_perf - start_perf} nanoseconds")
Elapsed time using perf_counter_ns: 28892300 nanoseconds
process_time() function
The process_time()
function returns the value (in fractional seconds) of the sum of the system and user CPU time of the current process.
It does not include time elapsed during sleep. This can be useful for profiling Python code.
Let’s see an example of how to use process_time()
to measure CPU time for code execution:
import time start_time = time.process_time() # code execution for i in range(1000000): pass end_time = time.process_time() cpu_time = end_time - start_time print(f"CPU time: {cpu_time} seconds")
Output:
CPU time: 0.07189000000003485 seconds
In this example, time.process_time()
is called before and after a loop execution.
The process_time function measures the CPU time as the difference between the end time and the start time without including the wait time. The precise time output can vary based on your system’s performance.
process_time_ns() function
For higher precision, you can use the process_time_ns()
function behaves similarly to process_time()
, but it returns the time as an integer number of nanoseconds.
import time start_proc = time.process_time_ns() for i in range(1000000): pass end_proc = time.process_time_ns() cpu_time = end_proc - start_proc print(f"CPU process time using process_time_ns: {end_proc - start_proc} nanoseconds")
CPU process time using process_time_ns: 31250000 nanoseconds
Python Time Mastery
For me, the use of the time
module is ingrained into my coding routine. It comes in handy more often than you’d think, and I still remember a particular project that depended heavily on its usage.
Our client was a global logistics company and they were facing a serious issue. They had thousands of transactions every hour, all taking place in different time zones.
They needed a system to accurately record and report the time of these transactions, taking into account the diverse time zones involved.
Their existing system was not up to the task, and that’s where my team and I came in.
I remember starting off by importing the time
and pytz
modules, pytz
being a third-party library that allows precise and cross platform timezone calculations.
import time from pytz import timezone
We decided to start with creating a function that would take a Unix timestamp and a timezone as inputs and return the local time in that timezone.
def convert_to_local_time(unix_timestamp, tz): tz = timezone(tz) local_time = time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(unix_timestamp)) return tz.localize(local_time)
The function would first use time.gmtime()
to convert the Unix timestamp to GMT, then it would localize it to the given timezone using tz.localize()
. It worked perfectly.
Then came the second requirement: they wanted to calculate the time elapsed between two timestamps. As simple as it sounds, this is not a trivial problem due to the need to account for time zones and daylight savings.
So, I created another function using the time
module.
def time_difference(timestamp1, timestamp2, tz): t1 = convert_to_local_time(timestamp1, tz) t2 = convert_to_local_time(timestamp2, tz) # calculate the difference in seconds diff = abs(t2 - t1).total_seconds() return diff
Here, I first converted both timestamps to the local timezone, and then used the .total_seconds()
method of the timedelta object returned by subtracting the two datetime objects to calculate the difference in seconds.
With these two functions, we had a good foundation. But this was not enough.
To fully meet our client’s needs, we had to build an entire system around these functions, capable of handling thousands of transactions per hour, and displaying this information in a clear, comprehensible format.
But that, as they say, is another story. For now, let it suffice to say that the time
module was central to our solution.
Further Reading
https://docs.python.org/3/library/time.html
Mokhtar is the founder of LikeGeeks.com. He is a seasoned technologist and accomplished author, with expertise in Linux system administration and Python development. Since 2010, Mokhtar has built an impressive career, transitioning from system administration to Python development in 2015. His work spans large corporations to freelance clients around the globe. Alongside his technical work, Mokhtar has authored some insightful books in his field. Known for his innovative solutions, meticulous attention to detail, and high-quality work, Mokhtar continually seeks new challenges within the dynamic field of technology.