Here's the full code, incorporating explanations and a visual representation:
import time
# Get the current time as a timestamp (seconds since epoch)
current_time_seconds = time.time()
print("Timestamp (seconds since epoch):", current_time_seconds)
# Get the current time in a readable format
current_time_string = time.ctime(current_time_seconds)
print("Readable format:", current_time_string)
# Format the time using strftime()
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S") # Format: YYYY-MM-DD HH:MM:SS
print("Formatted time:", formatted_time)
# Get local time and UTC time
local_time = time.localtime()
print("Local time:", time.strftime("%Y-%m-%d %H:%M:%S", local_time))
utc_time = time.gmtime()
print("UTC time:", time.strftime("%Y-%m-%d %H:%M:%S", utc_time))
# Pause execution for 5 seconds
time.sleep(5)
Key points:
- The time module provides functions for working with time in Python.
- time.time() returns the current time as a timestamp (seconds since epoch).
- time.ctime() converts a timestamp to a readable string format.
- time.strftime() formats time according to specified format codes.
- time.localtime() and time.gmtime() return local time and UTC time, respectively.
- time.sleep() pauses execution for a specified number of seconds.