SoFunction
Updated on 2025-03-05

Summary of access and conversion of time in Python standard library

Module introduction

The time module is one of Python's standard libraries and provides a variety of time-related functions. It allows the user to obtain the current time, perform operations on time intervals, and process conversions related to date and time. This module provides many functions, such as calculating time difference, pausing programs, formatting time strings, etc.

Most of the functions of this module are closely related to the system's clock operation and support the time formats of a variety of different platforms and systems.

Use scenarios

  • Get the current time: Get the current timestamp, formatting time, date, etc.
  • Time conversion: Convert timestamps to human-readable time formats, or convert formatted times to timestamps.
  • Delay and control: Pauses program execution for a period of time, which is suitable for controlling the speed of program execution.
  • Performance measurement: Measure the execution time of the program.
  • Set the time zone: Set and get the time zone of the local time.

Main categories

kind describe
struct_time Returns a structured time object provided by the localtime() or gmtime() function, including year, month, date, hour, minute, seconds and other information.

Main functions

function describe
time() Returns the timestamp of the current time (number of seconds elapsed after the 1970 epoch).
sleep(seconds) Pauses the program execution specified number of seconds.
localtime([secs]) Convert seconds to structured time to local time.
gmtime([secs]) Convert seconds to structured time to Greenwich Standard Time (UTC).
strftime(format[, t]) Returns the formatted time according to the given formatted string.
strptime(string, format) Parse the time string according to the given format string.
perf_counter() Returns a high-precision time counter, usually used to measure time intervals.
process_time() Returns the CPU execution time of the program, ignoring sleep and wait times.

 - time()

Returns the current timestamp, the number of seconds elapsed since January 1, 1970 (Unix Era). It can be used to measure time intervals, obtain time stamps, etc.

import time
timestamp = ()
print("Current timestamp:", timestamp)

- sleep()

Let the program pause execution for the specified number of seconds. Suitable for scenarios where program execution is required, such as pausing at certain task intervals.

import time
print("Start")
(3)  # Pause for 3 secondsprint("End")

- localtime()

Convert timestamps to local timestruct_timeObject. If no parameter is passed in, it returns the local time of the current time by default.

import time
time_obj = ()
print(time_obj.tm_year)  # Get Yearprint(time_obj.tm_mon)  # Get Monthprint(time_obj.tm_mday)  # Get Dayprint(time_obj.tm_hour)  # Get hoursprint(time_obj.tm_min)  # Get minutesprint(time_obj.tm_sec)  # Get seconds

- gmtime()

Convert timestamps to Greenwich Mean Time (UTC)struct_timeObject. If no parameter is passed in, it returns the UTC time of the current time by default.

import time
utc_time = ()
print(utc_time)  # Output the current UTC Time structure

- strftime()

Returns the formatted time according to the given formatted string. Commonly used tostruct_timeConvert objects to readable time formats.

import time
formatted_time = ("%Y-%m-%d %H:%M:%S", ())
print("Formatted time:", formatted_time)

- strptime()

Parses the time string based on the given format string and returnsstruct_timeObject. Suitable for parsing time strings.

import time
time_str = "2025-01-14 15:30:00"
parsed_time = (time_str, "%Y-%m-%d %H:%M:%S")
print("Parsed time:", parsed_time)

- perf_counter()

Returns a high-precision counter, usually used to measure time intervals. Suitable for program performance analysis and time measurement.

import time
start = time.perf_counter()
# Perform certain actionsend = time.perf_counter()
print(f"Elapsed time: {end - start} seconds")

- process_time()

Returns the CPU execution time of the program, excluding the system sleep time. Suitable for calculating the execution time of a program, especially when it comes to CPU-intensive tasks.

import time
start = time.process_time()
# Perform certain calculationsend = time.process_time()
print(f"CPU time: {end - start} seconds")

Things to note

  • Timestamp and local time:() returns the number of seconds (timestamps) since the Unix epoch, while localtime() and gmtime() can be converted to structured local time or UTC time.
  • Daylight saving time (DST): In some time zones, daylight saving time may affect time calculations, and time zone differences need to be paid attention to.
  • High-precision timer:perf_counter() provides a higher precision time counter suitable for performance analysis.
  • CPU time and actual time: process_time() only calculates the CPU execution time, ignoring the waiting and sleep time of the program.

Summarize

The time module provides Python with a variety of functions of processing time and date, which is suitable for a variety of time-related scenarios, including obtaining the current time, formatting time, pausing program execution, calculating program running time, etc. Through these features, developers can more efficiently handle time tasks, perform performance measurements, and perform program scheduling.

This is the end of this article about accessing and converting time of Python Standard Library. For more related content of Python Standard Library, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!