How To Get The Current Time In Python

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:

  1. time – Provides time-related functions and is part of the Python standard library.
  2. 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

Step 2: Get the current time using the time.time() function

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

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

Step 2: Get the current time using the datetime.datetime.now() function

This function returns a datetime.datetime object representing the current date and 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:

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.