Epoch in Python
A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in Python.
To run the program:
In Python, we use the time
module to get the current time since the Unix epoch, and the datetime
module to convert between timestamps and datetime objects.
The time.time()
function returns the current time in seconds since the Unix epoch as a floating-point number. We can multiply this value by 1000 or 1e9 to get milliseconds or nanoseconds, respectively.
To convert a timestamp back into a datetime object, we use datetime.fromtimestamp()
.
Next, we’ll look at another time-related task: time parsing and formatting.