Time¶
Time in Python is recorded in seconds. Any given time is recorded as the number of seconds since 1st January 1970 (referred at as the epoch).
We will use two different libraries to deal with time:
Both are part of the standard library that comes packaged with Python.
Pausing¶
The sleep
method pauses the program calculation and waits. The argument passes the wait time in seconds.
1from time import sleep
2
3print("Started")
4
5sleep(2)
6
7print("Two seconds later")
For more information check this freeCOdeCamp article.
Current time¶
The now
method returns the current local date and time. We also use the strftime
method to format the date. There are many formatting codes.
1from datetime import datetime
2
3now = datetime.now()
4
5# display time 24 hour
6print(now.strftime("%H:%M:%S"))
7
8# display tme 12 hour
9print(now.strftime("%I:%M:%S %p"))
For more information check this freeCodeCamp artilce
Current date¶
Both today
will return today’s date, while now
will return today’s date and time.
The return objects can be refined by using the dot notation asking for the:
year
month
day
hour
minute
second
microsecond
1from datetime import date
2from datetime import datetime
3
4# display today's date
5print(date.today())
6
7# display custom date
8now = datetime.now()
9print(f"{now.day}/{now.month}/{now.year}")
Calculate elapsed time¶
Since time is recorded in seconds, can perform calculations between two times.
1import time
2
3start = time.perf_counter()
4time.sleep(2)
5end = time.perf_counter()
6
7print(f"Elapsed time: {end - start} sec")