python
Get current timestamp in Python
In this post, we are going to explain the Python modules and methods that can be used to get the current timestamp.
import time
timestamp = time.time()
print(timestamp)
Output
1643920477.7901955
We are using the time module here to get the current timestamp. We are importing the time module using the import keyword.
import time
Then we are using the time() function of the time module to get the current timestamp.
Current timestamp in Python using datetime module
We can also use the Python datetime module to get the current timestamp in Python. All you need to do is import the datetime module in your Python code and use its datetime() function.
Code Example
import datetime;
current_timestamp = datetime.datetime.now().timestamp()
print(current_timestamp)
Output
1643995600.095005
If you do not want to use the float value of the timestamp, you can convert it to int using the Python int() function and pass the timestamp value to it.
print(int(current_timestamp))
Output
1643995909
Was this helpful?
Similar Posts
- Get current date in Python (Multiple Formats)
- How to get current file path in Python
- Filter by current time - n hours SQLAlchemy
- [Python] The get() method on Python dicts and its "default" arg
- To get url param details from get request in Django
- [Python] Get nodeid, module, function name using Pytest request built-in fixture
- [Python] Using inspect.stack() to get module name, path, function name