Get Unix time in Python

Here is an example of complete code which gets current unix time, convert it to struct_time, and then format it in a human-readable format:

import time

# Get the current Unix time
current_time = time.time()
print(f"Current Unix time: {current_time}")

# Convert the Unix timestamp to a struct_time in UTC 
struct_time = time.gmtime(current_time)
print(f"Struct time: {struct_time}")

# format struct_time in a human-readable format
time_formatted = time.strftime("%Y-%m-%d %H:%M:%S", struct_time)
print(f"Time formatted: {time_formatted}")

This will give you output in this format:

Current Unix time: 1623155816.546617
Struct time: time.struct_time(tm_year=2022, tm_mon=11, tm_mday=11, tm_hour=4, tm_min=30, tm_sec=16, tm_wday=4, tm_yday=316, tm_isdst=0)
Time formatted: 2022-11-11 04:30:16

You can also create struct_time directly from current time by using gmtime() function without passing any argument, it will return struct_time of current time. Also, You can customize the formatting string passed to strftime() function to display the time in different format.

Also, keep in mind that the time.time() function returns the current time in seconds since the Unix epoch in the system’s timezone. If you need the time in a different timezone, you’ll need to use a library like pytz or pendulum which provide timezone support and handling.