← Back to Articles
Tutorial

How to Get Current Time in Python

Learn how to get the current time in Python using simple methods and examples. Perfect for beginners and experts alike.

Getting the current time in Python is a common task in many applications, such as logging and time-stamping. Python provides several ways to retrieve the current time, making it versatile and easy to implement.

The most straightforward way to get the current time in Python is by using the 'datetime' module. This module provides the 'datetime.now()' method, which returns the current local date and time. You can also use the 'time' module to get the current time in seconds since the epoch, using 'time.time()'.

When working with time in Python, it is best to use timezone-aware datetime objects, especially in applications that may deal with multiple time zones. The 'pytz' library can be very helpful in managing time zones effectively.

A common mistake when working with current time in Python is not accounting for time zones, which can lead to inaccurate time calculations. Always ensure that your datetime objects are timezone-aware when necessary.

Code Examples

Example 1

from datetime import datetime

current_time = datetime.now()
print('Current Time:', current_time)

Example 2

import time

current_time_seconds = time.time()
print('Current Time in seconds since epoch:', current_time_seconds)

More Python Tutorials