How to get current time in Python

Python is a popular programming language that is widely used for web development, data analysis, and artificial intelligence. One of the most common tasks when working with Python is getting the current time. Whether you need to log an event, schedule a task, or simply display the time on your application, Python provides several built-in functions to help you retrieve the current time in a variety of formats.

Getting Current Time using Python’s time module

The time module in Python provides a simple way to get the current time in seconds since the Epoch. To retrieve the current time, you can use the time() function, which returns the number of seconds since January 1, 1970, 00:00:00 UTC.

import time

current_time = time.time()
print(current_time)

This will output something like: 1619276707.625702

However, the output format is not very human-readable. To convert this timestamp to a more readable format, you can use the ctime() function, which returns a string representation of the current time.

import time

current_time = time.time()
print(time.ctime(current_time))

This will output something like: Wed Apr 28 16:04:09 2021

Using datetime module

Another way to get the current time in Python is to use the datetime module. This module provides more advanced date and time handling capabilities than the time module.

To retrieve the current time using the datetime module, you can use the datetime.now() function, which returns a datetime object representing the current time.

import datetime

current_time = datetime.datetime.now()
print(current_time)

This will output something like: 2021-04-28 16:04:09.125702

You can also format the output using the strftime() function, which allows you to specify the format of the output.

import datetime

current_time = datetime.datetime.now()
print(current_time.strftime("%Y-%m-%d %H:%M:%S"))

This will output something like: 2021-04-28 16:04:09

Summary and Conclusion

Getting the current time in Python is a simple task that can be accomplished using the time and datetime modules. Both modules provide built-in functions to retrieve the current time in a variety of formats, making it easy to use the current time in your Python applications. Whether you need to log events, schedule tasks, or simply display the time, Python’s built-in functions make it easy to work with dates and times.

Leave a Comment

Scroll to Top