Skip to main content

How to get the current timestamp in Python

How to get the current timestamp in Python.

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

Step 1: Import the necessary modules

To get the current timestamp, we need to import the datetime module first. Open your Python script or interactive Python shell and add the following line at the beginning:

import datetime

Step 2: Get the current timestamp

Now that we have imported the datetime module, we can use it to get the current timestamp. To do this, we need to call the datetime class and use the now() method. This method returns the current date and time.

Here's an example of how to get the current timestamp:

current_timestamp = datetime.datetime.now()

Step 3: Format the timestamp (optional)

By default, the now() method returns the timestamp in a specific format. However, if you want to display the timestamp in a different format, you can use the strftime() method.

The strftime() method allows you to format the timestamp according to your needs. It takes a format string as an argument, which specifies how the timestamp should be formatted. Here are some commonly used format codes:

  • %Y: Year with century as a decimal number (e.g., 2022)
  • %m: Month as a zero-padded decimal number (e.g., 01, 02, ..., 12)
  • %d: Day of the month as a zero-padded decimal number (e.g., 01, 02, ..., 31)
  • %H: Hour (24-hour clock) as a zero-padded decimal number (e.g., 00, 01, ..., 23)
  • %M: Minute as a zero-padded decimal number (e.g., 00, 01, ..., 59)
  • %S: Second as a zero-padded decimal number (e.g., 00, 01, ..., 59)

Here's an example of how to format the timestamp:

formatted_timestamp = current_timestamp.strftime("%Y-%m-%d %H:%M:%S")

In this example, the timestamp is formatted as "YYYY-MM-DD HH:MM:SS".

Step 4: Print or use the timestamp

Finally, you can print or use the current timestamp as needed in your program. Here's an example of how to print the timestamp:

print("Current timestamp:", current_timestamp)

And here's an example of how to print the formatted timestamp:

print("Formatted timestamp:", formatted_timestamp)

That's it! You now know how to get the current timestamp in Python. Feel free to use this knowledge to timestamp your data, log events, or perform any other time-related tasks in your Python programs.