Get Current Timestamp Using Python (original) (raw)
Last Updated : 05 May, 2025
A **timestamp is a sequence of characters that represents the date and time at which a particular event occurred, often accurate to fractions of a second. Timestamps are essential in logging events, tracking files, and handling date-time data in various applications. There are **3 different ways to get the current timestamp in Python, let’s explore these methods.
Using the time Module
The time module provides the time() function, which returns the current time in seconds since the Unix epoch.
python `
import time
ts = time.time() print(ts)
`
**Explanation: time.time() returns the current time as a floating-point number, where the integer part is the seconds and the decimal part represents fractions of a second.
Using the datetime Module
The datetime module provides the now() function to get the current date and time, and the timestamp() method converts it to a timestamp.
python `
import datetime;
ct = datetime.datetime.now() print("current time:", ct)
ts = ct.timestamp() print("timestamp:", ts)
`
Output
current time: 2025-05-02 05:44:35.538966 timestamp: 1746164675.538966
**Explanation:
- datetime.datetime.now() gives the current date and time.
- .timestamp() converts this to the timestamp (seconds since the epoch).
Using the calendar Module
The calendar module can be used along with time.gmtime() to get the current GMT (Greenwich Mean Time), which can then be converted to a timestamp using calendar.timegm().
python `
import calendar; import time;
gmt = time.gmtime() print("gmt:", gmt)
ts = calendar.timegm(gmt) print("timestamp:", ts)
`
Output
gmt: time.struct_time(tm_year=2025, tm_mon=5, tm_mday=2, tm_hour=5, tm_min=44, tm_sec=35, tm_wday=4, tm_yday=122, tm_isdst=0) timestamp: 1746164675
**Explanation:
- time.gmtime() gets the current time in GMT as a tuple.
- calendar.timegm() converts this tuple into a timestamp (seconds since the epoch).
- Output prints the current GMT time and its corresponding timestamp.