How to find the system time in Python
In this tutorial, we will learn about how to find the system time i.e the current time of the system using the Python modules.
There are several ways and module to find the current time of the system. Here, we will use datetime module and time module to find the current time.
Getting Current Time Of The System in Python
First, we use the time module to find the current time of the system.
Steps 1: Import the time module
Step 2: Calling the localtime() class from the time module and storing the output in System_time variable.
Step 3: Printing the System time.
import time print(time.time()) System_time = time.localtime(time.time()) print("Local current time :", System_time)
Output:
Time function output in sec 1578669620.8800426 Local current time : time.struct_time(tm_year=2020, tm_mon=1, tm_mday=10, tm_hour=20, tm_min=50, tm_sec=20, tm_wday=4, tm_yday=10, tm_isdst=0)
Here, time.time() returns the number of seconds passed since 1 January 1970. And also, localtime() class return the output is not in good readable format.
So there are many way function or class which return the time in readable format. Here the simple methods which return the output in readable format.
import time #method 1 System_time1 = time.asctime(time.localtime(time.time())) print("\nAsctime function output:", System_time1) #method 2 System_time2 = time.ctime(time.time()) print("\nCtime function output:", System_time2)
Output:
Asctime function output: Fri Jan 10 21:02:08 2020 Ctime function output: Fri Jan 10 21:02:08 2020
Another Way To Find Current Time
We can also find the current time using another module i.e datetime module. Let’s see in example.
Step 1: Import the datetime module.
Step 2: Calling the datetime.now() class which return the time of the system and we stored in the system_time variable.
Step 3: Printing the output.
import datetime system_time = datetime.datetime.now() print("\nSystem Time is:", system_time)
Output:
System Time is: 2020-01-10 21:11:54.117483
Here, in the output datetime.now() class return the time in the format YYYY-HH-MM-MS.
Here. datetime module also allows us to modify the format according to our requirement. Let’s see in example.
import datetime system_time = datetime.datetime.now() print("\nSystem Time is:", system_time) print(system_time.strftime("\nYYYY-MM-DD-%Y-%m-%d HH-MM-SS-%H:%M:%S")) print(system_time.strftime("\nYYYY-MM-DD %Y/%m/%d")) print(system_time.strftime("\nHH-MM-SS %H:%M:%S")) print(system_time.strftime("\nHH(12H)-MM-SS-PM/AM %I:%M:%S %p")) print(system_time.strftime("\nDay = %a,Month = %b, Date = %d,Year = %Y"))
Output:
System Time is: 2020-01-10 21:16:14.118094 YYYY-MM-DD-2020-01-10 HH-MM-SS-21:16:14 YYYY-MM-DD 2020/01/10 HH-MM-SS 21:16:14 HH(12H)-MM-SS-PM/AM 09:16:14 PM Day = Fri,Month = Jan, Date = 10,Year = 2020
You can also learn:
How to find roots of polynomial in Python
Leave a Reply