Wednesday, December 25, 2024
Google search engine
HomeLanguagesHow to convert DateTime to integer in Python

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.

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




# importing the datetime module
import datetime
 
# Getting todays date and time using now() of
# datetime class
current_date = datetime.datetime.now()
 
# Printing the current_date as the date object itself.
print("Original date and time object:", current_date)
 
# Retrieving each component of the date
# i.e year,month,day,hour,minute,second and
# Multiplying with multiples of 100
# year - 10000000000
# month - 100000000
# day - 1000000
# hour - 10000
# minute - 100
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




# importing the datetime module
import datetime
 
# Getting todays date and time using now() of datetime
# class
current_date = datetime.datetime.now()
 
# Printing the current_date as the date object itself.
print("Original date and time object:", current_date)
 
# Using the strftime() of datetime class
# which takes the components of date as parameter
# %Y - year
# %m - month
# %d - day
# %H - Hours
# %M - Minutes
# %S - Seconds
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

RELATED ARTICLES

Most Popular

Recent Comments