How to Convert Datetime to Epoch in Python?

Python provides a “datetime” library for manipulating dates and times. The “datetime” library has multiple functions that deal with time intervals, dates, data conversion, etc.

The “Epoch” time, also known as POSIX time, indicates how many seconds have passed since January 1, 1970, 00:00:00 (UTC).

To convert specific Datetime to Epoch, the following methods are used in Python:

Method 1: Using the timegm() Function of the Calendar Module

In the code example given below, the “timegm()” function is used along with the “datetime()” function to convert the DateTime to Epoch:

Code:

import datetime,calendar
date = datetime.datetime(2023, 1, 1, 0, 0)
output = calendar.timegm(date.timetuple())
print(output)

In the above code:

  • The datetime value is passed as an argument to the “datetime.datetime()” function.
  • The “date.tuple()” represents the time and object as a tuple that contains information about the date and time
  • The “timegm()” function accepts the tuple and retrieves the corresponding number of seconds since the epoch (1970-1-1).

Output:

The above output shows the conversion of DateTime “2023-01-01” to Epoch.

Method 2: Using timestamp()

In the example code given below, the “timestamp()” function is used to convert the Datetime to Epoch:

Code:

import datetime
output = datetime.datetime(2023, 1, 1, 0, 0).timestamp()
print(output)

In the above code, the “timestamp()” function is used to find the timestamp of DateTime “2023-01-01” and will retrieve the number of seconds that have passed since the epoch.

Output:

The above output shows the conversion of DateTime “2023-01-01” to Epoch.

Method 3: Using total_seconds()

In this method, we manually subtract the specific date from the starting date of the epoch and convert it into seconds using the “total_seconds()” function.

Code:

import datetime
date = datetime.datetime(2023,1,1,0,0)
output= ( date - datetime.datetime(1970,1,1)).total_seconds()
print(output)

In the above code:

  • The “datetime()” function is used to represent the specific date in datetime format.
  • The specified date is subtracted from the epoch start date “1970-01-01”, and the final output is calculated by converting it into seconds using the “total_seconds()” function.

Output:

The above output uses the explicit method to convert the DateTime “2023-01-01” to Epoch.

Conclusion

To convert the Datetime to Epoch, the “timegm()” function, “timestamp()” function, and “total_seconds()” are used in Python. The “timegm()” function accepts the specific date-time value and retrieves the Unix timestamp value. Similarly, the “timestamp” and explicit method with the “total_Seconds()” are used to convert the specific Datetime to the epoch in Python. This post presented a precise guide on converting the Datetime to the epoch in Python using multiple examples.