How to convert DateTime to integer in Python
Last Updated :
30 Aug, 2021
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.
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.
Python3
import datetime
current_date = datetime.datetime.now()
print ( "Original date and time object:" , current_date)
print ( "Date and Time in Integer Format:" ,
current_date.year * 10000000000 +
current_date.month * 100000000 +
current_date.day * 1000000 +
current_date.hour * 10000 +
current_date.minute * 100 +
current_date.second)
|
Output:
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.
Code:
Python3
import datetime
current_date = datetime.datetime.now()
print ( "Original date and time object:" , current_date)
print ( "Date and Time in Integer Format:" ,
int (current_date.strftime( "%Y%m%d%H%M%S" )))
|
Output:
Original date and time object: 2021-08-10 15:55:19.738126
Date and Time in Integer Format: 20210810155519
Share your thoughts in the comments
Please Login to comment...