Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Python Time Module: Access and Conversion

Tech May 7 4

The time module provides various functions related to time. Additional functionality can also be found in the datetime and calendar modules.

Although this module can be imported on all platforms, not all functions within the module are available on every platform. Most functions in this module are implemented by calling the same-named function in the C library of the platform. Because the semantics may vary by platform, it is recommended to consult the relevant documentation for the specific platform when using these functions.

Terms

Below are explanations of some terminology.

2.1 UTC

Coordinated Universal Time (UTC) is an abbreviasion for Coordinated Universal Time. It was previously known as Greenwich Mean Time (GMT). The use of UTC instead of CUT is a compromise between English and French (Temps Universel Coordonné), not a mistake.

2.2 DST

Daylight Saving Time (DST) is an abbreviation that adjusts local time (usually by one hour) during a certain period of the year. DST rules are very complex (determined by local laws) and vary each year. The C language library has a table that records DST rules for different regions (in practice, the C library usually reads this table from a system file for flexibility). From this perspective, this table is the only authoritative source of DST rules.

2.3 epoch

The starting point of time, which is the return value of time.gmtime(0). This is 1970-01-01, 00:00:00 (UTC) on all platforms.

2.4 epoch seconds

The total number of seconds since the epoch time point, typically excluding leap seconds. On all POSIX-compliant platforms, leap seconds are not counted in the total number of seconds.

Conventions

Below are explanations of some conventions.

3.1 Limited past, limited future

This module can only handle a limited time interval and may not handle dates and times before the epoch or in the distant future. The boundary for the distant future is determined by the C library; for 32-bit systems, it is usually around 2038.

3.2 Two-digit years, 68 over 69 under

The strptime() function can parse two-digit year representations when receiving the %y format code. When parsing two-digit years, the function maps values 69–99 to 1969–1999 and values 0–68 to 2000–2068 according to POSIX and ISO C standards.

3.3 Old Unix clock

Due to platform limitations, the precision of various real-time functions may be lower than the precision required by their values or parameters. For example, on most Unix systems, the clock frequency is only 50 or 100 times per second.

On the other hand, the precision of time() and sleep() is better than their Unix equivalents: time is represented as a float, time() returns the most accurate time available, and sleep() accepts time with non-zero decimal parts.

3.4 Time conversion relationships

Time values returned by gmtime(), localtime(), and strptime() are accepted by asctime(), mktime(), and strftime(). These are sequences of 9 integers. The return values of gmtime(), localtime(), and strptime() also provide attribute names for each field. See the struct_time section for more details.

Use the following functions to convert between time representations:

Functions

4.1 time.asctime([t])

Converts a tuple or struct_time returned by gmtime() or localtime() into a string in the form: 'Sun Jun 20 23:21:05 1993'. The day field is two characters long, and if the day is a single digit, it is padded with zero, for example: 'Wed Jun 9 04:26:40 1993'. If t is not provided, the current time returned by localtime() is used. asctime() does not use locale information. Note that unlike the C function of the same name, asctime() does not add a trailing newline.

time_tuple = (2023, 7, 5, 12, 30, 45, 0, 0, 0)
print(time.asctime(time_tuple))
print(time.asctime())

# Output
Mon Jul  5 12:30:45 2023
Sat Feb 24 09:25:52 2024

4.2 time.ctime([secs])

Converts a time expressed in seconds since the epoch to a string in the form: 'Sun Jun 20 23:21:05 1993' representing local time. The day field is two characters long, and if the day is a single digit, it is padded with a space, for example: 'Wed Jun 9 04:26:40 1993'. If secs is not provided or is None, the current time returned by time() is used. ctime(secs) is equivalent to asctime(localtime(secs)). ctime() does not use locale information.

current_time = time.ctime()
print(current_time)
print(time.ctime(100000))

# Output
Sat Feb 24 09:51:26 2024
Fri Jan  2 11:46:40 1970

4.3 time.gmtime([secs])

Converts a time expressed in seconds since the epoch to a UTC struct_time, where the DST flag is always zero. If secs is not provided or is None, the current time returned by time() is used. Seconds with fractions less than one are ignored. For more information about the struct_time object, see above. For the inverse operation of this function, see calendar.timegm().

current_time = time.gmtime()
print(current_time)
print(time.gmtime(100000))

# Output
time.struct_time(tm_year=2024, tm_mon=2, tm_mday=24, tm_hour=1, tm_min=56, tm_sec=43, tm_wday=5, tm_yday=55, tm_isdst=0)
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=2, tm_hour=3, tm_min=46, tm_sec=40, tm_wday=4, tm_yday=2, tm_isdst=0)

4.4 time.localtime([secs])

Similar to gmtime() but converts to local time. If secs is not provided or is None, the current time returned by time() is used. When DST applies to the given time, the DST flag is set to 1. localtime() may raise an OverflowError if the timestamp is outside the range supported by the platform's C localtime() or gmtime() functions and will raise an OSError if either fails. This is typically limited between 1970 and 2038.

current_time = time.localtime()
print(current_time)
print(time.localtime(100000))

# Output
time.struct_time(tm_year=2024, tm_mon=2, tm_mday=24, tm_hour=9, tm_min=57, tm_sec=58, tm_wday=5, tm_yday=55, tm_isdst=0)
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=2, tm_hour=11, tm_min=46, tm_sec=40, tm_wday=4, tm_yday=2, tm_isdst=0)

4.5 time.mktime(t)

This is the inverse function of localtime(). Its argument is a struct_time or a complete 9-tuple (as DST flag is required; use -1 if unknown), which represents local time, not UTC. It returns a float to be compatible with time(). If the input value cannot represent a valid time, an OverflowError or ValueError is raised (depending on whether Python or the underlying C library catches the invalid value). The earliest date it can geenrate depends on the platform.

time_tuple = (2023, 7, 6, 12, 0, 0, 1, 199, -1)
timestamp = time.mktime(time_tuple)
print(timestamp)

# Output
1688616000.0

4.6 time.monotonic()

Returns a value of a monotonic clock (in seconds as a float), which is a clock that cannot go backwards. This clock is not affected by system clock updates. The reference point of the return value is undefined, so only the difference between two calls is valid.

print(time.monotonic())

# Output
14666.671

4.7 time.perf_counter()

Returns a value of a performance counter (in seconds as a float), which is a clock with the highest possible accuracy for measuring short durations. It includes time spent in sleep and operates across the entire system. The reference point of the return value is undefined, so only the difference between two calls is valid.

# Record start time
start_time = time.perf_counter()
# Perform some computation or operation
for i in range(1000000):
    pass
# Record end time
end_time = time.perf_counter()
# Calculate execution time
elapsed_time = end_time - start_time
print(f"Execution time: 0.1085 seconds")

# Output
Execution time: 0.0256365 seconds

(Continued...)

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.