Get Current time in Python
In this article, you will learn how to get your locale zone's current time and different time zones.
There are several ways we can use to get the current time in Python.
Example: Current time using datetime object
from datetime import datetime
now = datetime.now()
current_time = now.strftime("%H:%M:%S")
print("Current time =", current_time)
Output
Current time = 12:08:22
In the above program, we have imported datetime
class from the datetime module. We used the now()
method to get a datetime
object that contains the current date and time.
Then with the help of the datetime.strftime()
method, we created a string representing the current time.
If we want to create directly a time
object containing the current time, we can write the following program.
from datetime import datetime
now = datetime.now().time()
print("now =", now)
print("type(now) =", type(now))
Output
now = 12:19:16.283080
type(now) = <class 'datetime.time'>
Example: Current time using time module
Python also offers a way to get the current time by using the time module.
import time
t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
print("Current time =", current_time)
Output
Current time = 12:27:30
CodeTexte
Example: Current time of a timezone
We can use pytz module, if we need to find the current time of a specific time zone.
from datetime import datetime
import pytz
tz_NY = pytz.timezone("America/New_York")
datetime_NY = datetime.now(tz_NY)
print("New York time =", datetime_NY.strftime("%H:%H:%S"))
tz_Paris = pytz.timezone("Europe/Paris")
datetime_Paris = datetime.now(tz_Paris)
print("Paris time =", datetime_Paris.strftime("%H:%M:%S"))
Output
New York time = 08:08:04
Paris time = 13:36:04