Python | time.time() method (original) (raw)
Last Updated : 28 Aug, 2019
Time module in Python provides various time-related functions. This module comes under Python’s standard utility modules. **_time.time()_** method of Time module is used to get the time in seconds since epoch. The handling of leap seconds is platform dependent.Note: The epoch is the point where the time starts, and is platform dependent. On Windows and most Unix systems, the epoch is January 1, 1970, 00:00:00 (UTC) and leap seconds are not counted towards the time in seconds since the epoch. To check what the epoch is on a given platform we can use **_time.gmtime(0)_**.
Syntax: time.time()Parameter: No parameter is requiredReturn type: This method returns a float value which represents the time in seconds since the epoch.
Code #1: Use of **_time.time()_** method
Python3 `
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)
`
Output:
epoch is: Thu Jan 1 00:00:00 1970 Time in seconds since the epoch: 1566454995.8361387
Code #2: Calculate seconds between two date
Python3 `
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)
`