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.

import time
from datetime import datetime

def main():
    # Use time.time() to get elapsed time since the Unix epoch in seconds
    now = time.time()
    print(datetime.fromtimestamp(now))

    # Get seconds, milliseconds, and nanoseconds
    print(int(now))
    print(int(now * 1000))
    print(int(now * 1e9))

    # You can also convert integer seconds or nanoseconds
    # since the epoch into the corresponding datetime
    print(datetime.fromtimestamp(int(now)))
    print(datetime.fromtimestamp(now))

if __name__ == "__main__":
    main()

To run the program:

$ python epoch.py
2023-05-17 12:34:56.789012
1684326896
1684326896789
1684326896789012000
2023-05-17 12:34:56
2023-05-17 12:34:56.789012

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.