Python time gmtime() method
Description
The Python time gmtime() function converts a timestamp into a struct_time object in the UTC time zone (zone 0). The optional parameter sec represents the number of seconds since 1970-1-1.
A struct_time object contains various information about time, such as year, month, day, hour, minute, and so on.
Syntax
gmtime() method syntax:
time.gmtime([ sec ])
Parameters
- sec -- the number of seconds to convert into a time.struct_time object; it is a timestamp.
Return Value
This function has no return value.
Example
The following example shows how to use the gmtime() function:
Example
#!/usr/bin/python
-- coding: UTF-8 --
import
time
Get the GMT representation of the current time
gmt_time
=
time
.
gmtime
(
)
(
"GMT time:"
)
(
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 a 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
)
(
"GMT time of the specified timestamp:"
)
(
gmt_time_custom
)
Please note that the struct_time object returned by gmtime() is a named tuple, and its fields can be accessed by index or by attribute.
For example, to get the year, you can use gmt_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
(
"Year:"
)
(
year
)