Python - How To Get the Current Time in Python

ID : 380

viewed : 82

Tags : PythonPython DateTime

vote vote


Python is a versatile programming language with the generous support of libraries and modules to perform general tasks efficiently and with less code. One such domain is date and time. Dealing with dates and times can be a frustrating task at times. But Python has good support for it as well. Python has dedicated libraries that ease the pain of dealing with dates and times. They make it easier to perform operations over dates and times and perform mathematical functions such as addition and difference. They make performing conversions a piece of cake, giving developers more time to worry about the business login. This article will talk about getting the current time using one such Python module.

Get the Current Time Using the datetime Module in Python

The datetime module has a now() function that can be used to get the current date and time in Python. The following code depicts how to use this function to get the current time. Note that the now() function returns the local time instead of the UTC time. To get the UTC time, we can use the `utcnow() function.

from datetime import datetime  date = print(date) 


2021-10-17 17:03:40.456934 

As we can see, the output has both date and time. We can further call functions to get individual values. We can use the date() function to get the date and time() function to get the time. Refer to the following code for the same.

from datetime import datetime  date = print(date) print("Date:", print("Time:", date.time())	 


2021-10-17 17:09:45.754117 Date: 2021-10-17 Time: 17:09:45.754117 

Furthermore, we can also use the strftime() function to format the output of the three function calls above. Following is an example of the same.

from datetime import datetime  date = print("Before Formatting") print("DateTime:", date) print("Date:", print("Time:", date.time()) print("After Formatting") print("DateTime:", date.strftime("%d %B, %Y %H:%M:%S")) # DD Month, YYYY HH:MM:SS print("Date:","%d %B, %Y")) # DD Month, YYYY print("Time:", date.time().strftime("%H:%M:%S")) # HH:MM:SS 


Before Formatting DateTime: 2021-10-17 17:21:31.446824 Date: 2021-10-17 Time: 17:21:31.446824 After Formatting DateTime: 17 October, 2021 17:21:31 Date: 17 October, 2021 Time: 17:21:31 

To learn more about strftime(), refer to the official documentation . To explore the format codes, refer .

  • Related HOW TO?