当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Python time.localtime()用法及代码示例


Python中的时间模块提供了各种与时间相关的函数。该模块属于Python的标准实用程序模块。

time.localtime()时间模块的方法用于将自纪元以来的时间(以秒为单位)转换为time.struct_time对象在当地时间。
将自纪元以来的给定时间(以秒为单位)转换为time.struct_timeUTC中的对象,time.gmtime()使用方法。

此方法返回一个time.struct_time具有命名元组接口的对象。以下是其中的值time.struct_time Object :


index 属性
0 tm_year (例如,1993年)
1 tm_mon 范围[1,12]
2 tm_mday 范围[1,31]
3 tm_hour 范围[0,23]
4 tm_min 范围[0,59]
5 tm_sec 范围[0,61]
6 tm_wday 范围[0,6],星期一为0
7 tm_yday 范围[1,366]
8 tm_isdst 0、1或-1
不适用 tm_zone 时区名称的缩写
不适用 tm_gmtoff 以秒为单位偏移UTC以东
用法: time.localtime([secs])

参数:
secs(可选):整数或浮点值,表示以秒为单位的时间。指定秒的分数将被忽略。如果未提供secs参数或无,则使用time.time()方法返回的当前时间。

返回类型:此方法返回“ time.struct_time”类的对象。

代码1:用于time.localtime()方法

# Python program to explain time.localtime() method 
  
# importing time module 
import time 
  
# If secs parameter 
# is not given then 
# the current time as 
# returned by time.time() method 
# is used 
  
# Convert the current time in seconds 
# since the epoch to a 
# time.struct_time object in Local time 
obj = time.localtime() 
  
# Print the time.struct.time object 
print(obj) 
  
# We can change it to 
# Day Mon date Hour:Min:Sec year 
# format using time.asctime() method 
t = time.asctime(obj) 
print(t)
输出:
time.struct_time(tm_year=2019, tm_mon=8, tm_mday=22, tm_hour=10, tm_min=3,
tm_sec=15, tm_wday=3, tm_yday=234, tm_isdst=0)
Thu Aug 22 10:03:15 2019

代码2:用于time.localtime()方法

# Python program to explain time.localtime() method 
  
# importing time module 
import time 
  
# Time in seconds 
# since the epoch 
secs = 950000000
  
# Convert the given time in seconds 
# since the epoch to a 
# time.struct_time object in local time 
# using time.localtime() method 
obj = time.localtime(secs) 
  
# Print the time.struct_time object 
print("time.struct_time object for seconds =", secs) 
print(obj) 
  
  
# Time in seconds 
# since the epoch 
secs = 950000000.81956
  
# Convert the given time in seconds 
# since the epoch to a 
# time.struct_time object in local time 
# using time.localtime() method 
obj = time.localtime(secs) 
  
# Print the time.struct_time object 
print("\ntime.struct_time object for seconds =", secs) 
print(obj) 
  
  
# Output for secs = 950000000 
# and secs = 950000000.81956 
# will be same beacause 
# fractions in 950000000.81956 
# i.e .81956 will be ignored
输出:
time.struct_time object for seconds = 950000000
time.struct_time(tm_year=2000, tm_mon=2, tm_mday=8, tm_hour=14, tm_min=23,
tm_sec=20, tm_wday=1, tm_yday=39, tm_isdst=0)

time.struct_time object for seconds = 950000000.81956
time.struct_time(tm_year=2000, tm_mon=2, tm_mday=8, tm_hour=14, tm_min=23,
tm_sec=20, tm_wday=1, tm_yday=39, tm_isdst=0)

参考: https://docs.python.org/3/library/time.html#time.localtime



相关用法


注:本文由纯净天空筛选整理自ihritik大神的英文原创作品 Python | time.localtime() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。