Get the Current Date and Time in Python

To import the current date (year, month, day) and time (hour, minute, second), you have to import the datetime module.

Display date and time

First, let’s display the current date and time using the print function.

This code will display both: the date and time:

2020-03-31 11:30:51.232310

This is the default format. After the second, there is a fraction of the second (the 1-microsecond precision).

Current date and time in the specified format

If you don’t like this format, you can change it to the exact format you like. To do it, you have to use the strftime function from the time module.

This code returns this result:

2020-03-31, 13:17:40

Get the current year, month, day, hour, minute, and second separately

So far, we returned the current date and time in one print function.

If you want to have access to a single element, you can do it.

For each result, we are using the print function. You can display even microseconds if you need them.