Skip to main content

How to get the current date in Python

How to get the current date in Python.

Here's a step-by-step tutorial on how to get the current date in Python:

  1. Import the datetime module:

    • In Python, the datetime module provides classes for manipulating dates and times. To use it, you need to import the module first. You can do this by adding the following line at the beginning of your code:
      import datetime
  2. Get the current date using datetime.date.today():

    • The datetime module provides the date class, which has a static method called today() that returns the current date. You can use this method to get the current date in the format YYYY-MM-DD. Here's an example:

      import datetime

      current_date = datetime.date.today()
      print(current_date)
  3. Format the current date using strftime():

    • If you want to format the current date in a specific way, you can use the strftime() method. This method allows you to specify a format string that defines how the date should be displayed. Here's an example that formats the current date as DD/MM/YYYY:

      import datetime

      current_date = datetime.date.today()
      formatted_date = current_date.strftime("%d/%m/%Y")
      print(formatted_date)
  4. Get the current date and time using datetime.datetime.now():

    • If you also need the current time along with the date, you can use the datetime class from the datetime module. The now() method returns a datetime object representing the current date and time. Here's an example:

      import datetime

      current_datetime = datetime.datetime.now()
      print(current_datetime)
  5. Format the current date and time using strftime():

    • Similar to formatting the date, you can also format the date and time using the strftime() method. Here's an example that formats the current date and time as YYYY-MM-DD HH:MM:SS:

      import datetime

      current_datetime = datetime.datetime.now()
      formatted_datetime = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
      print(formatted_datetime)

That's it! You now know how to get the current date in Python using the datetime module. Feel free to experiment with different formatting options to display the date and time in the desired format.