Python Time Module
import time
# returns epoch time
seconds = time.time()
print(seconds)
import time
# returns epoch time
seconds = time.time()
print(seconds)
# -------------------------------------------------
current_time_1 = time.ctime(seconds)
current_time_2 = time.ctime()
print("Current time is ",current_time_1)
print("Current time is ",current_time_2)
1593627527.3428385 Current time is Wed Jul 1 11:18:47 2020 Current time is Wed Jul 1 11:18:47 2020
import time
print("going for a 4 second sleep")
time.sleep(4)
# stops the program execution for 3 seconds
print("ohh i wake up")
going for a 4 second sleep ohh i wake up
- Day of week : eg , mon (Monday )
- Month of year : eg, jul ( July)
- Day of month : eg. 1
- Hours, minutes & seconds using 24 hour clock notation
- year : eg, 2020
time.struct_time Class
time.struct_time(tm_year=2018, tm_mon=12, tm_mday=27, tm_hour=6, tm_min=35, tm_sec=17, tm_wday=3, tm_yday=361, tm_isdst=0)
Index | Attribute | Values |
---|---|---|
0 | tm_year | 0000, ...., 2018, ..., 9999 |
1 | tm_mon | 1, 2, ..., 12 |
2 | tm_mday | 1, 2, ..., 31 |
3 | tm_hour | 0, 1, ..., 23 |
4 | tm_min | 0, 1, ..., 59 |
5 | tm_sec | 0, 1, ..., 61 |
6 | tm_wday | 0, 1, ..., 6; Monday is 0 |
7 | tm_yday | 1, 2, ..., 366 |
8 | tm_isdst | 0, 1 or -1 |
The values (elements) of the time.struct_time
object are accessible using both indices and attributes.
The method like gmtime( ) and localtime( ) returns the struct_time tuple.
4. time.localtime( ) :
import time
epoch = time.time()
print(epoch)
result = time.localtime(epoch)
print(result)
print("Current Day ",result.tm_mday)
print("Current Year ",result.tm_year)
1593638249.778398
time.struct_time(tm_year=2020, tm_mon=7, tm_mday=1, tm_hour=14, tm_min=17, tm_sec=29, tm_wday=2, tm_yday=183, tm_isdst=1)
Current Day 1
Current Year 2020
5. time.gmtime( ) :
import time
epoch = time.time()
print(epoch)
result = time.gmtime(epoch)
print(result)
print("Current Day ",result.tm_mday)
print("Current Year ",result.tm_year)
OUTPUT :
1593638506.1140974
time.struct_time(tm_year=2020, tm_mon=7, tm_mday=1, tm_hour=21, tm_min=21, tm_sec=46, tm_wday=2, tm_yday=183, tm_isdst=0)
Current Day 1
Current Year 2020
import time
epoch = time.time()
print(epoch)
result = time.gmtime(epoch)
print(result)
new_epoch = time.mktime(result)
print(new_epoch)
1593638859.8717556
time.struct_time(tm_year=2020, tm_mon=7, tm_mday=1, tm_hour=21, tm_min=27, tm_sec=39, tm_wday=2, tm_yday=183, tm_isdst=0)
1593667659.0
import time
epoch = time.time()
print(epoch)
result = time.gmtime(epoch)
print(result)
timestamp = time.asctime(result)
print('Time stamp is ',timestamp)
1593639179.9078994
time.struct_time(tm_year=2020, tm_mon=7, tm_mday=1, tm_hour=21, tm_min=32, tm_sec=59, tm_wday=2, tm_yday=183, tm_isdst=0)
Timestamp is Wed Jul 1 21:32:59 2020
No comments