You are currently viewing How to get Current Time in Python?

There are several ways to get the current time in Python. Along with using the built-in time, datetime modules, and third parties libraries, that you can use to get the current time. In this article, We will discuss differnt methods, and different scenarios where each method can be useful and provide examples to demonstrate how to use them.

Advertisements

Each method has its own advantages and disadvantages, depending on the specific requirements of the project. This article will help you better understand the best methods to use in different situations, so you can choose the one that best suits your needs.

1. Quick Examples of Python How to Get Current Time

Here are some quick examples that we will be discussing in this article. These examples will give you a high-level overview of the methods we will be covering, and we’ll discuss each one in more detail later in the article.


import time
from datetime import datetime, date

#  Using time.time()
current_time = time.time()

# Using time.localtime()
current_time = time.localtime()
hour = current_time.tm_hour
minute = current_time.tm_min
second = current_time.tm_sec


# Using time.asctime()
current_time = time.asctime()

# Using time.ctime()
current_time = time.ctime()

# Using datetime.datetime.now().time()
current_time = datetime.now().time()

# Using datetime.datetime.utcnow().time()
current_time = datetime.utcnow().time()

# Using datetime.datetime.today().time()
current_time = datetime.today().time()

2. time Module – Get Current Time in Python

The time module in Python provides several methods for getting the current time. Whether you need the local time, UTC time, or a specific time zone, there’s a function or method that can help. Below is a list of them.

2.1 Use time.localtime()

The time.localtime() method returns the current time in the local timezone as a struct_time object, which represents a tuple containing nine values representing different components of a date and time.


import time
current_time = time.localtime()

hour = current_time.tm_hour
minute = current_time.tm_min
second = current_time.tm_sec

print(f"The current time is {hour}:{minute}:{second}")
# Output : The current time is 19:30:53

2.2 Use time.time()

The time.time() method returns the current time as a floating-point number representing the number of seconds since the epoch (00:00:00 UTC, January 1, 1970).

This method is useful when you need to measure the elapsed time between two points in your code.


my_time = time.time()
print(my_time)
# Output : 1676470115.6388943

Below is another useful example, to measure the time taken to execute a piece of code.


start_time = time.time()
# code to be timed goes here
end_time = time.time()

elapsed_time = end_time - start_time
print(f"Total Time Taken: {elapsed_time} seconds")

# Output: Total time taken : 0 Seconds

2.3 Use time.gmtime()

time.gmtime() is similar to time.localtime(), but it returns a struct_time object that represents the current time in UTC. This means that the time zone information in the struct_time object will be zero.


current_time = time.gmtime()

print(current_time.tm_hour, current_time.tm_min, current_time.tm_sec)

# Output: 14 31 20

2.4 Use time.asctime()

The time.asctime() method returns a string representing the time in a readable format. It takes a time tuple as an argument and returns a string representing the date and time in the format “Day Month Date HH:MM:SS Year”.

If no argument is passed to the method, it will use the current local time.


# Get current local time
local_time = time.localtime()

# Convert time tuple to readable string
readable_time = time.asctime(local_time)

# Print readable time
print(readable_time)

# Output : Wed Feb 15 19:33:41 2023

2.5 Use time.ctime()

The time.ctime() method is another way to get the current time as a string. This method returns a string representing the current time in the format “Day Month Date Time Year”.

This method takes no arguments, and it returns the current time in the local time zone. In the following example, we will see how to use time.ctime() to get the current time as a string.


current_time = time.ctime()
print("Current time is:", current_time)
# Output : Current time is: Wed Feb 15 19:40:11 2023

3. Comparison of time Module Methods

Below is the comparison table that summarizes the features of each method for getting the current time using the time module in Python:

MethodReturns Unix timestampConverts to local timeConverts to UTC timeReturns human-readable format
time.time()YesNoNoNo
time.localtimeNoYesNoNo
time.gmtime()NoNoYesNo
time.asctime()NoYesNoYes
time.ctime()NoYesNoYes
Comparision Table

Some of these methods may be more appropriate for certain use cases than others. I hope this comparison table helps you choose the best method for your specific use case!

4. Using the datetime module

The datetime module in Python provides more powerful and flexible ways of working with dates and times compared to the time module. We will explore some of the best methods to get the current time using the datetime module.

4.1 Use datetime.now().time()

datetime.now() returns the current date and time, while time() returns the time component of the datetime object. It’s important to note that datetime.now() returns the time in the local timezone.


from datetime import datetime

current_time = datetime.now().time()
print("Current time:", current_time)

# Output : Current time: 20:00:42.552275

4.2 Use datetime.utcnow().time()

This method is similar to datetime.now().time(), but returns the UTC time instead of the local time. This is useful when you need to work with time zones or compare times across different regions.


current_time_utc = datetime.utcnow().time()
print("Current UTC Time:", current_time_utc)

# Output : Current UTC Time: 15:06:57.273715

4.3 Use datetime.now().timetuple()

The timetuple() method is used to convert the date object into a time tuple, which is a named tuple that contains the year, month, day, hour, minute, second, weekday, Julian day, and daylight savings flag. It returns a time.struct_time object containing the time components of the current time.


current_time_tuple = datetime.now().timetuple()
hour =current_time_tuple[3]
minute =current_time_tuple[4]
second = current_time_tuple[5]
current_time = f'{hour}:{minute}:{second}'  
print(current_time)
# Output : 20:28:47

4.4 Use datetime.today().time()

Last but not the least methdo to get the current time in python is datetime.today().time(). See the following example.


current_time = datetime.today().time()
print(current_time)
# Output : 20:46:52.001756

5. Get Current Time in a Specific Timezone

The best method to get current time in a specific timezone is to use pytz library along with the datetime module. You can use pytz.timezone() to get the desired timezone object and then use it to localize a datetime object.

Remeber you need to install the pytz library.


import pytz
from datetime import datetime

eastern = pytz.timezone('US/Eastern')
dt_eastern = datetime.now(eastern)
print(dt_eastern.time())
# Output : 10:54:37.248663

This will return a datetime object representing the current date and time in the specified timezone.

6. Best Way to Get the current Time

The best way to get the current time in Python will depend on the specific requirements of your application. Here are some general guidelines that can help you.

6.1 Current Time in Your Local Timezone

If You want get the current time in your local timezone then the best method for this scenario is datetime.datetime.now(). This mehod returns a datetime object representing the current date and time in your local timezone.

6.2 Current Time in UTC

UTC is the primary time standard by which the world regulates clocks and time. If you want the current itme accoring to UTC, then the best method for this scenario is datetime.datetime.utcnow(). This method provides the full precision of a datetime object and is useful if you need to work with UTC times.

This method is also very useful when you need to perform arithmetic operations with dates and times.

6.3 Need Time Component of the Current Time

Let’s say you need the hour, minute and second components serparately. In this this scenario the best method is datetime.datetime.now().time(), which returns a time object representing the current time in your local timezone.

6.4 Need a String Representation

The best method for this scenario depends on the specific format you need. If you need a standard format recognized by other applications or systems, you can use time.asctime() or time.ctime().

If you need a custom format, you can use datetime.datetime.now().strftime(), which allows you to specify the format using placeholders for various date and time components.

7. Summary and Conclusion

We have Explained how to get current time in Python. There are multiple methods to get the current time so we have provided a section to decide the best method for you. I hope you have a clear understanding. Let me know if you have any question.

Happy Learning!!!