In this tutorial, we will learn how to get the current time in Python. Parsing and formatting the current time is a common task in many applications, and Python provides several built-in libraries to make this process easy and efficient.
Python has two built-in libraries that we can use to get the current time:
- time – Provides time-related functions and is part of the Python standard library.
- datetime – Provides classes for manipulating dates and times, and is also part of the Python standard library.
Method 1: Using the time library
To get the current time using the time library, you need to follow these steps:
Step 1: Import the time library
1 |
import time |
Step 2: Get the current time using the time.time() function
1 |
current_time = time.time() |
This function returns the current time in seconds since the epoch (January 1, 1970, 00:00:00 (UTC)). To convert this value into a human-readable format, we can use the time.localtime() function.
Step 3: Convert the current time into a human-readable format
1 |
local_time = time.localtime(current_time) |
1 2 3 4 5 6 |
import time current_time = time.time() local_time = time.localtime(current_time) print(local_time) |
Output:
time.struct_time(tm_year=2022, tm_mon=1, tm_mday=24, tm_hour=12, tm_min=30, tm_sec=30, tm_wday=0, tm_yday=24, tm_isdst=0)
The local_time variable now contains a time.struct_time object, which is a named tuple representing the current time with fields like tm_year, tm_mon, tm_mday, etc.
Method 2: Using the datetime library
Alternatively, you can use the datetime library to get the current time in Python:
Step 1: Import the datetime library
1 |
import datetime |
Step 2: Get the current time using the datetime.datetime.now() function
1 |
current_time = datetime.datetime.now() |
This function returns a datetime.datetime object representing the current date and time.
1 2 3 4 5 |
import datetime current_time = datetime.datetime.now() print(current_time) |
Output:
2022-01-24 12:30:30.123456
Finally, you can also get the current time without the date information using the datetime.time class:
1 |
current_time_only = datetime.datetime.now().time() |
1 2 3 4 |
import datetime current_time_only = datetime.datetime.now().time() print(current_time_only) |
Output:
12:30:30.123456
Conclusion
In this tutorial, we learned two methods to get the current time in Python: using the time library and the datetime library.
Both libraries provide easy-to-use functions for retrieving the current time and formatting it in a human-readable manner. Depending on your needs, you can choose the one that suits your requirements best.