How to convert DateTime to integer in Python
Python provides a module called DateTime to perform all the operations related to date and time. It has a rich set of functions used to perform almost all the operations that deal with time. It needs to be imported first to use the functions and it comes along with python, so no need to install it separately.
Here, we deal with a special date object. So to convert the given date to integer, we can follow the following method.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Method 1: Using multiplication with 100’s
In this method, we will multiply each component, of the date with multiples of 100 and add them all to convert them into integers.
Original date and time object: 2021-08-10 15:51:25.695808 Date and Time in Integer Format: 20210810155125
Method 2: Using datetime.strftime() object
In this method, we are using strftime() function of datetime class which converts it into the string which can be converted to an integer using the int() function.
Syntax : strftime(format)
Returns : It returns the string representation of the date or time object.
Original date and time object: 2021-08-10 15:55:19.738126 Date and Time in Integer Format: 20210810155519