How to get current timestamp in Python?

By IncludeHelp Last updated : February 17, 2024

A timestamp is a sequence of characters or encoded information that is used to identify when a certain event occurred. In this tutorial, we will learn how to get current timestamp in Python.

Getting current timestamp

The below are the steps to get the current timestamp in Python:

  • Import the datetime module.
  • Call the datetime.datetime.now() method to get the current date time
  • Store the current date time in a variable.
  • Now, to get the current datetime, call the timestamp() method with the variable having the current date time.
  • In conclusion, the datetime.datetime.now().timestamp() is used to get the current date time. Consider the below code:
    import datetime
    print(datetime.datetime.now().timestamp())

Python code to get current timestamp

The below Python code prints the current date, time, and timestamp:

# Importing the datetime module
import datetime

# Get current date and store in a variable
ctime = datetime.datetime.now()
print("The current time is:", ctime)

# Getting the current timestamp
ctimestamp = ctime.timestamp()
print("The current timestamp is:", ctimestamp)

Output

The output of the above program is:

The current time is: 2024-02-17 22:05:31.905245
The current timestamp is: 1708207531.905245

To understand the above program, you should have the basic knowledge of the following Python topics:

 
 

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.