The time.gmtime()
function converts seconds representing a timestamp since the epoch into a UTC ( Coordinated Universal Time) in form of a struct_time
object. A struct_time
object has attributes that makes it easier to access the individual components of time i.e year, month, day, hour, minutes, seconds, etc.
The main difference between localtime() and gmtime()
functions is that localtime()
returns the local time of the machine where the code is running, while gmtime()
returns the current Greenwich Mean Time (GMT) including timezone offset.
gmtime(secs = None)
secs |
Optional argument for seconds representing time since the epoch to be converted into UTC time. If not given, the function will use the currentsystem time. |
The function returns a struct_time
object representing the time in Coordinated Universal Time (UTC). The returned object includes a time tuple that includes fields such as year, month, day, hour, minute, second, and microsecond, along with other attributes related to date and time.
Using the gmtime()
function to get the current UTC time..
#importing the time module
import time
current_time = time.gmtime()
print(current_time)
Using gmtime()
with a timestamp given.
#import the time module
import time
past_timestamp = 1521002400
#get the utc time
struct_obj = time.gmtime(past_timestamp)
print(struct_obj)
Accessing individual elements of a struct_time object
We can access the individual components of the timestamp represented by a struct_time
object using its various attributes.
get the individual components of a timestamp
#importing the time module
import time
current_time = time.gmtime()
print("year: ", current_time.tm_year)
print("month: ", current_time.tm_mon)
print("Day: ", current_time.tm_mday)
print("Hour: ", current_time.tm_hour)
print("minute: ", current_time.tm_min)
print("second: ", current_time.tm_sec)
Convert a struct_time object into a formatted string
We can convert the returned struct_time
object into a formatted, human-readable string.
Convert a struct_time object into a string
import time
timestamp = 1599496800
time_obj = time.gmtime(timestamp)
formatted_date = time.strftime("%d %b %Y %I:%M:%S %p", time_obj)
print(formatted_date)
You can on time module usage to see more on formatting date and time.