Python time gmtime() Method


Description

The Python time gmtime() function converts a timestamp to a struct_time object in the UTC time zone (zone 0). The optional parameter sec represents the number of seconds since January 1, 1970.

The struct_time object contains various information about time, such as year, month, day, hour, minute, etc.

Syntax

The syntax of the gmtime() method is:

time.gmtime([ sec ])

Parameters

  • sec -- The number of seconds to convert to a time.struct_time type object, which is a timestamp.

Return Value

This function has no return value.

Example

The following example demonstrates the usage of the gmtime() function:

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time

# Get the GMT representation of the current time
gmt_time = time.gmtime()
print("GMT time:")
print(gmt_time)

The output of the above example is:

GMT时间:
time.struct_time(tm_year=2023, tm_mon=11, tm_mday=23, tm_hour=6, tm_min=27, tm_sec=52, tm_wday=3, tm_yday=327, tm_isdst=0)

Get the GMT representation of the specified timestamp:

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time

timestamp = 1609459200  # 2021-01-01 00:00:00
gmt_time_custom = time.gmtime(timestamp)
print("GMT time for the specified timestamp:")
print(gmt_time_custom)

Please note that the struct_time object returned by gmtime() is a named tuple, and each of its fields can be accessed via index or attribute.

For example, to get the year, you can usegmt_time.tm_year:

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import time

# Get the GMT representation of the current time
gmt_time = time.gmtime()
year = gmt_time.tm_year
print("Year:")
print(year)
Other Extensions