當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。