Handling time in Python is a crucial aspect of many applications. Whether you want to timestamp an event, measure runtime, create a timer, or simply display the current time, Python provides several tools making it very straightforward to work with time. In this tutorial, we will cover different ways to get the current time in Python.
Step 1: Using Time Module
Python’s time module provides various functions to manipulate time. To get the current time, we can use the time() function from the time module as in the example below:
1 2 3 |
import time current_time = time.time() print("Current Time is:", current_time) |
The time() function returns the current time in seconds since the epoch as a floating point number. It does not format the date in the way humans are accustomed to reading it.
Step 2: Formatting Time using Ctime or Asctime
Current time retrieved using the time() function isn’t very readable. To get a more readable format, we can use the ctime() or asctime() functions from the time module as shown below:
1 2 3 |
import time readable_time = time.ctime() print("Formatted Time is:", readable_time) |
Both ctime() and asctime() functions return a string representing the current time in the form: ‘Tue Apr 16 11:34:12 2021’.
Step 3: Using Datetime Module
Python’s datetime module also provides functions to work with date and time. The function datetime.now() returns the current date and time:
1 2 3 |
from datetime import datetime current_time = datetime.now() print("Current Time is:", current_time) |
The output of datetime.now() will be in the format 2021-04-16 13:08:18.356941
.
Full Code Block Below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import time from datetime import datetime # Using time module current_time = time.time() print("Current Time is:", current_time) # Formatting the time readable_time = time.ctime() print("Formatted Time is:", readable_time) # Using datetime module current_time = datetime.now() print("Current Time is:", current_time) |
Conclusion
As you can see, getting the current time in Python is straightforward. Whether you want to track the execution time of your program, timestamp events in a log file, or just display the current date and time in a readable format, Python’s time and datetime modules have you covered.