In this tutorial, learn how to find the current date and time in Python. The short answer is: use python time()
to get the current time. The current date contains the day, month, and year to show in the output. It also contains the clock current from your system generated clock time.
You can generate integer type date as well as the string character type. The integer type date will show the time in the format 2019-02-10. While the string character type will show the date as Sun Feb 10.
It depends upon you which method you prefer to find your current date and time in Python. So, let’s see this method in detail with examples given in each section.
Find the Current Date and Time in Python
If you want to get today’s current date and time, you have to first import the datetime
library of Python. After that, you have to use the now()
function with that datetime
keyword. Check the example below to find your dates.
1 2 |
from datetime import datetime print(datetime.now()) |
Output
The above example showing the output contains the today’s date and the current time. Check the format of the time in the output. It contains integer type hours, minutes, and seconds with a year, month, and day.
Get Only The Current Time in Python
Sometimes, you may want to get only the current time while programming in Python. Due to that reason, you have to use the above example and add the time()
. This will gives you the current time in the output. Check the example below to get an idea of how to use the function.
1 2 |
from datetime import datetime print(datetime.now().time()) |
Output
The above example gives only the current time and not the date. The time containing the hour, minutes, and seconds on the clock.
How to Find the Current Date and Time in Character String
In addition to above all, you can also get the current date and time in character string format. To get the required output, you have to first import the time
library of Python. After that, you have to use the functionctime()
as given in the below example.
1 2 |
import time print(time.ctime()) |
Output
The above example showing the day as Sun, month as Feb and day as 10. You will also get the current time of the system in the output. After all these in the output, you will get the year as 2019.
- Execute Python program or code on Windows
- delete multiple items of Dictionary using Python
- How to Find the current version of Python
I hope you like this post on how to get the current date and time in Python.
Reference