📜  Python| time.time() 方法

📅  最后修改于: 2022-05-13 01:55:07.974000             🧑  作者: Mango

Python| time.time() 方法

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

Time 模块time.time()方法用于获取自纪元以来的时间(以秒为单位)。闰秒的处理取决于平台。

注意:纪元是时间开始的点,并且取决于平台。在 Windows 和大多数 Unix 系统上,纪元是 1970 年 1 月 1 日 00:00:00 (UTC),并且闰秒不计入纪元以来的时间(以秒为单位)。要检查给定平台上的纪元,我们可以使用time.gmtime(0)

代码 #1:使用time.time()方法

# Python program to explain time.time() method
  
# importing time module
import time
  
# Get the epoch
obj = time.gmtime(0)
epoch = time.asctime(obj)
print("epoch is:", epoch)
  
# Get the time in seconds
# since the epoch
time_sec = time.time()
  
# Print the time 
print("Time in seconds since the epoch:", time_sec)
输出:
epoch is: Thu Jan  1 00:00:00 1970
Time in seconds since the epoch: 1566454995.8361387

代码 #2:计算两个日期之间的秒数

# Python program to explain time.time() method
  
# importing time module
import time
  
# Date 1
date1 = "1 Jan 2000 00:00:00"
  
# Date 2
# Current date
date2 = "22 Aug 2019 00:00:00"
  
# Parse the date strings
# and convert it in 
# time.struct_time object using
# time.strptime() method
obj1 = time.strptime(date1, "% d % b % Y % H:% M:% S")
obj2 = time.strptime(date2, "% d % b % Y % H:% M:% S")
  
# Get the time in seconds
# since the epoch
# for both time.struct_time objects
time1 = time.mktime(obj1)
time2 = time.mktime(obj2)
  
print("Date 1:", time.asctime(obj1))
print("Date 2:", time.asctime(obj2))
  
  
# Seconds between Date 1 and date 2
seconds = time2 - time1
print("Seconds between date 1 and date 2 is % f seconds" % seconds)
输出:
Date 1: Sat Jan  1 00:00:00 2000
Date 2: Thu Aug 22 00:00:00 2019
Seconds between date 1 and date 2 is 619747200.000000 seconds

参考: https://docs。 Python.org/3/library/time.html#time.time