How to Get Current Date and Time in Python

Last Updated on May 24, 2024 by Roshan Parihar

To get the current date and time in Python in the format YYYY-MM-DD H:M:S, use the datetime.now() function and import the datetime library.

You can also generate integer type date as well as the string character type like ‘Sun Feb DD H:M:S YYYY’ using time.ctime(). Let’s find out with the examples given below.

Get the Current Date and Time in YYYY-MM-DD H:M:S Format in Python

If you want to get the current date and time, you have to first import the datetime library of Python. After that, you have to use the datetime.now() function to find today’s dates.

Example 1

Output

2024-05-24 10:37:48.115604

The above example showing the output contains the current date and time. Check the format of the time in the output. It contains integer type hours, minutes, and seconds with a year, month, and day.

Find Current Date in Format YYYY-MM-DD Using datetime.today().strftime() in Python

You can use the datetime.today().strftime() function and pass '%Y-%m-%d' as its argument to get current date only.

Example 2

Output

2024-05-24

The above example showing the output contains the today’s date only. It is the in the format YYYY-MM-DD.

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 give you the current time in the output. Check the example below to get an idea of how to use the function.

Example 3

Output

21:06:22.859871

The above example gives only the current time and not the date. The time contains the hour, minutes, and seconds on the clock.

Find Today’s Date-time in Character String

In addition to the above, 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.

Example 4

Output

Sun Feb 10 21:07:53 2019

The above example shows 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 format 2019.