In this tutorial, we will learn How To Get The Current Time In Python we can do in two different ways first is by the DateTime object and second by the time module so let’s explore both methods to get the current time in Python.
Ways To Get The Current Time In Python
To get the current time in python we have two ways let’s explore both ways to get the current time along with the date of the day.
Time Using DateTime Method
To use this we need to import the datetime module from the library in python, And after that, we can simply use the now() function to get the time and date of the current day. And using DateTime.strtime() we can create a string that holds the time as their data only.
To implement and understand it in a better way just follow the code given below and learn to grow.
from datetime import datetime now = datetime.now() current_time = now.strftime("%H:%M:%S") print("Current Time =", current_time)
As here first, we have imported the datetime package and simply used the inbuild function to get the current time along with the date using now() function.
Time Using Time Module
We can also get the current time using a module called time let’s follow the code given for the same
import time t = time. localtime() current _time = time. strftime(" %H:%M:%S", t) print( current_time)
Here we have imported the time module and used the inbuild function current_time.
There is a provision to get the time on changing the time zone in that case we need to specify the time zone for the exact timing. for example have a look at the example.
from datetime import datetime import pytz # Get the timezone object for New York tz_NY = pytz.timezone('America/New_York') # Get the current time in New York datetime_NY = datetime.now(tz_NY)
It is a code to get the timing of Ney York similarly we can get the time of any time zone.
To learn more about How Do I Get The Current Time In Python visit Get Current time in Python
Also VisitMySQL Problems And Tutorials to learn more about MySQL and beta python for programing Solutions for other programing languages problems