Python - How To Get the Current Date in Python

ID : 387

viewed : 82

Tags : PythonPython DateTime

vote vote

96

This tutorial demonstrates how to get the current date in Python.

Use the datetime Module to Get the Current Date in Python

The module has utility functions specifically for date and time manipulations in Python. Within the module it has an object of the same name that has the function today() that returns the current date and time with the default date-time format.

As an example, import the datetime module and directly print the output of datetime.today().

from datetime import datetime  print(datetime.today()) 

Output:

2021-03-09 15:05:55.020360 

To modify the default format for the datetime, use the format and call the strftime() method that’s also built-in within the datetime module.

For example, to display the current date without the time, the format for that is %Y-%m-%d.

from datetime import datetime  print(datetime.today().strftime('%Y-%m-%d')) 

Output:

2021-03-09 

To include the time but without the seconds and milliseconds, the format for that would be %Y-%m-%d %H-%M.

from datetime import datetime  print(datetime.today().strftime('%Y-%m-%d %H:%M')) 

Output:

2021-03-09 15:05 

Another format would be to include the day of the week. In this example, we will use the month’s actual name.

from datetime import datetime  print(datetime.today().strftime('%A, %B %d, %Y %H:%M:%S')) 

Output:

Tuesday, March 09, 2021 15:05:55 

In summary, the datetime module can be used to get the current date by using the function today(). To extensively modify the default date format, strftime formatting can be followed and applied by using the strftime() function.

  • Related HOW TO?