Get Current Time in Python

How do I get the Python time now? How can I retrieve the current time in Python?

To get the python time now, you can start simple with the datetime module.

Here’s how:

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

This will give you the current date and time in the default format: YYYY-MM-DD HH:MM:SS.microseconds. It’s straightforward and perfect for general use.

Building on Yanisleidi’s response, if you’re looking for something different, you can use the time module to get the python time now.

Here’s how it works:

import time  
current_time = time.time()  
print(current_time)  # Output: Number of seconds since the epoch  

Want something more human-readable? Use time.ctime() to convert it:

current_time = time.ctime()  
print(current_time)  # Output: Current time in a nice, readable format  

It’s great for scenarios where you don’t need microseconds precision but still want quick, readable results.

Now, if you’re working across time zones and need timezone-aware current time, you can use the pytz library for precise control over the python time now.

Check this out:

from datetime import datetime  
import pytz  

timezone = pytz.timezone('Europe/Paris')  
current_time = datetime.now(timezone)  
print(current_time)  

This will give you the current time adjusted for the Paris timezone. You can switch the timezone to any region you need, and it’s especially useful for applications that need international compatibility.