datetime library can be imported to a Python program. It provides classes used in manipulating date and time in the Python code.
epoch is the starting point of measuring the time elapsed, and its value usually varies and depends on the platform being used.
This tutorial will discuss different methods to convert datetime to epoch in Python.
Use the Explicit Method to Convert Datetime to Epoch in Python
In this method, we take the current date and manually subtract it from the starting date and then convert it in seconds by using the
total_seconds() function and displaying it.
The initial date here is 1970/1/1.
The following code uses the explicit method to convert datetime to epoch in Python.
import datetime ts= (datetime.datetime(2019,12,1,0,0) - datetime.datetime(1970,1,1)).total_seconds() print(ts)
timestamp() Function to Convert Datetime to Epoch in Python
A Timestamp is a series of characters that dictates the value of when a particular event occurred.
Python provides a function
timestamp(), which can be used to get the timestamp of datetime since epoch.
The following code uses the
timestamp() function to convert datetime to epoch in Python.
import datetime ts= datetime.datetime(2019, 12,1, 0, 0).timestamp() print(ts)
This is a fairly easy method and provides us with accurate outputs.
Note that the
timestamp() function only works on Python 3.3+ and is not applicable for use in the older versions of Python.
strftime(format) Function to Convert Datetime to Epoch in Python
strftime(format) method is used to convert an object to a string based on the format specified by the user.
For the reverse of this process,
strptime() method is used.
The following code uses the
strftime(format) method to convert datetime to epoch in Python.
import datetime ts= datetime.datetime(2019, 12, 1, 0, 0).strftime('%s') print(ts)
strftime(format) might not always provide the correct solution. This method uses the
%s directive as an argument of
strftime, which Python doesn’t actually support. It could work because Python forwards
%s to the system’s
This method is not the most accurate method for conversion of datetime to epoch. It is not recommended to use this method simply because there are better and more accurate methods.
timegm Function to Convert DateTime to Epoch in Python
timegm() function takes a specific time value and returns its corresponding Unix timestamp value. The epoch is taken as 1970, and the POSIX encoding is assumed.
timegm() functions are the inverse of each other.
time libraries need to be imported to the Python program to use these functions.
calendar module provides us with the ability to output calendars and some additional and useful functions related to it.
The following code uses
timegm() function to convert the datetime to epoch.
import datetime import calendar d=datetime.datetime(2019, 12, 1, 0, 0) print ( calendar.timegm(d.timetuple()) )