How to use the time module in Python?

In Python, the time module offers functions and classes for handling time. Here are some commonly used functions in the time module along with examples of how to use them:

  1. Get the current timestamp.
import time

timestamp = time.time()
print("当前时间戳:", timestamp)
  1. Convert a timestamp to a time tuple.
import time

timestamp = time.time()
time_tuple = time.gmtime(timestamp)
print("时间元组:", time_tuple)
  1. Convert a time tuple to a timestamp.
import time

time_tuple = (2021, 5, 20, 12, 30, 0, 3, 140, 0)
timestamp = time.mktime(time_tuple)
print("时间戳:", timestamp)
  1. Format time:
import time

time_tuple = (2021, 5, 20, 12, 30, 0, 3, 140, 0)
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", time_tuple)
print("格式化时间:", formatted_time)
  1. Obtain the formatted string of the current time.
import time

current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print("当前时间:", current_time)

These are the methods commonly used in the time module, you can choose the appropriate function based on your specific needs to handle time.

bannerAds