0
0
PythonHow-ToBeginner · 3 min read

How to Get Timestamp in Python: Simple Guide

In Python, you can get the current timestamp using time.time() which returns the time in seconds since January 1, 1970. Alternatively, use datetime.datetime.now().timestamp() for a datetime object’s timestamp.
📐

Syntax

There are two common ways to get a timestamp in Python:

  • time.time(): Returns the current time in seconds as a floating-point number since the Unix epoch (January 1, 1970).
  • datetime.datetime.now().timestamp(): Returns the timestamp of the current local datetime as a float.
python
import time
import datetime

# Using time module
current_time = time.time()

# Using datetime module
current_datetime = datetime.datetime.now()
timestamp = current_datetime.timestamp()
💻

Example

This example shows how to get the current timestamp using both time and datetime modules and prints them.

python
import time
import datetime

# Get timestamp using time module
timestamp_time = time.time()
print(f"Timestamp using time.time(): {timestamp_time}")

# Get timestamp using datetime module
timestamp_datetime = datetime.datetime.now().timestamp()
print(f"Timestamp using datetime.datetime.now().timestamp(): {timestamp_datetime}")
Output
Timestamp using time.time(): 1700864987.123456 Timestamp using datetime.datetime.now().timestamp(): 1700864987.123456
⚠️

Common Pitfalls

One common mistake is to expect time.time() or datetime.timestamp() to return an integer. They return a float including fractions of a second.

Also, datetime.timestamp() returns the timestamp in local time, so beware of timezone differences if you compare it with UTC timestamps.

python
import datetime

# Wrong: expecting integer timestamp
timestamp = int(datetime.datetime.now().timestamp())
print(f"Integer timestamp (seconds only): {timestamp}")

# Right: keep float for precision
timestamp_precise = datetime.datetime.now().timestamp()
print(f"Precise timestamp (float): {timestamp_precise}")
Output
Integer timestamp (seconds only): 1700864987 Precise timestamp (float): 1700864987.123456
📊

Quick Reference

MethodDescriptionReturns
time.time()Current time in seconds since Unix epochfloat (seconds)
datetime.datetime.now().timestamp()Timestamp of current local datetimefloat (seconds)

Key Takeaways

Use time.time() to get the current timestamp as seconds since 1970-01-01 UTC.
datetime.datetime.now().timestamp() gives the timestamp of the current local time.
Timestamps are floats including fractions of a second for precision.
Be careful with timezones when using datetime timestamps.
Keep timestamps as floats unless you specifically need whole seconds.