SoFunction
Updated on 2025-04-25

Some common functions of Python's time module (various time-related functions)

PythontimeThe module provides various time-related functions, including obtaining the current time, processing time interval, performing time measurement, etc. The following is correcttimeA detailed introduction, usage, common usage, example code and running results of some commonly used functions in the module.

1. Get the current time

  • (): Returns the number of seconds since the Era (00:00:00 UTC on January 1, 1970), commonly known as Unix timestamp.
  • (): Returns a local timetime.struct_timeObject.
  • (): Returns a coordinated Universal Time (UTC)time.struct_timeObject.
import time
# Get the current time stamptimestamp = ()
print("Current timestamp:", timestamp)
# Get local timelocal_time = ()
print("Local time:", local_time)
# Get UTC timeutc_time = ()
print("UTC Time:", utc_time)

Run result (depending on your time zone and current time):

Current timestamp: 1715833304.1631322
Local time: time.struct_time(tm_year=2024, tm_mon=5, tm_mday=16, tm_hour=12, tm_min=21, tm_sec=44, tm_wday=3, tm_yday=137, tm_isdst=0)
UTC time: time.struct_time(tm_year=2024, tm_mon=5, tm_mday=16, tm_hour=4, tm_min=21, tm_sec=44, tm_wday=3, tm_yday=137, tm_isdst=0)

2. Time formatting

  • (format, time_tuple): Willtime.struct_timeThe object is formatted as a string.
  • (string, format): parse the string intotime.struct_timeObject.
import time
# Format local timeformatted_time = ("%Y-%m-%d %H:%M:%S", ())
print("Format local time:", formatted_time)
# parse time stringparsed_time = ("2021-09-10 10:22:47", "%Y-%m-%d %H:%M:%S")
print("Time after parsing:", parsed_time)

Running results:

Formatted local time: 2024-05-16 12:22:02
Time after parsing: time.struct_time(tm_year=2021, tm_mon=9, tm_mday=10, tm_hour=10, tm_min=22, tm_sec=47, tm_wday=4, tm_yday=253, tm_isdst=-1)

3. Delay execution

  • (seconds): The number of seconds that the program is paused.
import time
print("Start sleep...")
(2)  # Sleep for 2 secondsprint("The sleep ends!")

Running results:

Start sleeping...
(Wait 2 seconds)
Sleep ends!

4. Timestamp operation

Since the timestamp is a floating point number, you can directly perform addition and subtraction operations to represent the time interval.

import time
# Get the current time stampnow = ()
# 10 seconds laterfuture = now + 10
print("Time stamp after 10 seconds:", future)
#10 seconds agopast = now - 10
print("Time stamp 10 seconds ago:", past)

Running results:

Timestamp after 10 seconds: 1715833358.9650567
Timestamp 10 seconds ago: 1715833338.9650567

5. Calculate the code execution time

You can use()To calculate the execution time of a piece of code.

import time
start_time = ()
# Here is the code you want to calculate the execution timefor i in range(1000000):
    pass
end_time = ()
execution_time = end_time - start_time
print(f"Code execution time: {execution_time} Second")

Running results:

Code execution time: 0.03800845146179199 seconds

6. Time converted to the specified time zone

PythontimeThe module itself does not directly support time zone conversion, but you can use itpytzLibrary or Python 3.9+zoneinfoModules to do this. The following is a usepytzExample:

import time
import pytz
from datetime import datetime
# Get the current UTC timeutc_now = ()
print("UTC Time:", utc_now)
# Convert to New York Time (EST/EDT)new_york_tz = ('America/New_York')
new_york_time = utc_now.astimezone(new_york_tz)
print("New York Time:", new_york_time)

Running results:

UTC time: 2024-05-16 04:24:15.237127
New York Time: 2024-05-15 16:24:15.237127-04:00

Note: Before running the above code, you need to install it firstpytzLibrary, availablepip install pytzCommand to install. Installation and import of Python third-party libraries

7. Timer (execute tasks every certain time)

You can use()and a loop to create a simple timer.

import time
def timer_task():
    print("Timed task is being executed...")
while True:
    timer_task()
    (5)  # Execute every 5 seconds# Notice:The above code will loop infinitely,You may need a way to interrupt it,For example, set a flag variable or usetry/exceptcaptureKeyboardInterruptabnormal。

8. Get the date part of the timestamp

If you have a timestamp and just want to get its date part, you can convert the timestamp todatetimeObject, then extract the date.

import time
from datetime import datetime
timestamp = ()
dt_object = (timestamp)
date_only = dt_object.date()
print("Date Part:", date_only)

Running results:

Date part: 2024-05-16

These examples showtimeSome common usages of modules in Python. Depending on your specific needs, you may also need to combine other libraries or modules to implement more complex time-processing tasks.
Note: The timestamps are simply added and subtracted here, but the result is still the timestamp, not the human-readable date-time format. If you need to convert it to a readable format, you can use()or()Combined()Format.

This is the end of this article about Python time module - various time-related functions. For more related Python time module content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!