Convert Integers to Datetime in Pandas

In this Python tutorial, we will learn how to convert Integers to Datetime in Pandas DataFrame. Also, we will cover these topics.

  • Convert int to datetime in Pandas
  • Convert number to date in Pandas
  • Convert excel number to date in Pandas
  • Convert int column to datetime Pandas
  • Pandas convert datetimeindex to integer
  • Convert int to datetime in Pandas with nan
  • Convert int to datetime in Pandas without decimal
  • Convert int to datetime in Pandas string

Convert Integers to Datetime in Pandas

  • In this Program, we will discuss how to convert integers to Datetime in Pandas DataFrame by using Python.
  • By using Pandas.Datetime() method we can perform this particular task and to do this task first you have to check that the integer data must match the format specified.

Syntax:

Here is the Syntax of Pandas.Datetime() method

Pandas.to_datetime
                  (
                   arg,
                   errors='raise',
                   dayfirst='False',
                   yearfirst='False',
                   utc=None,
                   format=None,
                   exact=True,
                   unit=None,
                   infer_datetime_format=false,
                   origin='unix',
                   cache=True
                  )

Example:

Let’s take an example and check how to convert integers to datetime in Pandas Dataframe by using Python

import pandas as pd

new_dict = {'no_dates':  [19990320,20200416,20010828],
          'new_stats': ['Available','Available','Available']
          }

df = pd.DataFrame(new_dict, columns = ['no_dates','new_stats'])

df['no_dates'] = pd.to_datetime(df['no_dates'], format='%Y%m%d')

print (df)

In the above code, we have created three different dates with a format of (yyy-mm-dd). Now we will declare the dataframe object and assign dictionary ‘new_dict’ and column names in the list. Now use Pandas.to_Datetime() method to convert integers to Datetime.

Here is the execution of the following given code

Convert Integers to Datetime in Pandas
Convert Integers to Datetime in Pandas

Also, check: Python Pandas replace multiple values

Convert int to datetime in Pandas

  • Let us see how to convert int to datetime in Pandas DataFrame by using Python.
  • Here we can use the pd.to_datetime() method and this function will convert your integer data to a date format.

Syntax:

Here is the Syntax of pd.to_datetime() method

Pandas.to_datetime
                  (
                   arg,
                   errors='raise',
                   dayfirst='False',
                   yearfirst='False',
                   utc=None,
                   format=None,
                   exact=True,
                   unit=None,
                   infer_datetime_format=false,
                   origin='unix',
                   cache=True
                  )
  • It consists of few parameters
    • arg: This parameter specifies the object you want to convert to a datetime and object must be integer, string or float.
    • errors: By default, its value is ‘raise’ that represent the invalid parsing will raise an exception.
    • dayfirst: This parameter will help you to understand if your ‘day’ is first in your format and by default, its value is ‘False’.
    • yearfirst: It indicates if your year is first then try the format code option first and by default, it takes the ‘false’ value.
    • utc: This parameter is used if you want to convert your datetime with timezone.
    • format: This parameter is used to show the format codes of datetime.

Source Code:

import pandas as pd

new_int = 19981123
new_result=pd.to_datetime(str(new_int), format='%Y%m%d')
print(new_result)

In the above program, we have imported the Pandas library and then initialize an integer value with the variable name ‘new_int’. Now use the pd.to_datetime() method and assign str datatype along with ‘new_int’. Once you will print the ‘new_result’ then the output will display the Datetime format.

You can refer to the below Screenshot

Convert int to datetime in Pandas
Convert int to datetime in Pandas

Read: Python DataFrame to CSV

Convert number to date in Pandas

  • In this section, we will discuss how to convert the number to date in Pandas Dataframe by using Python.
  • In this example, we have to convert an integer numbers to date in Pandas Dataframe. To perform this task first we are going to use the pd.to_datetime() method and this will help the user to convert the number with date in Dataframe.

Example:

import pandas as pd

new_val = 20100820
new_dt = pd.DataFrame({'date':[new_val]*3})
new_dt['New_DateTime'] = new_dt['date'].apply(lambda m: pd.to_datetime(str(m), format='%Y%m%d'))
print(new_dt)

In the above code, we have created a dataframe object ‘new_dt’ and then pass the integer variable name ‘new_val’ along with *3 which means it will display three times. Now use the lambda function and it evaluates an expression for a given argument.

Here is the implementation of the following given code

Convert number to date in Pandas
Convert number to date in Pandas

Read: Get index Pandas Python

Convert excel number to date in Pandas

  • In this Program, we will discuss how to convert the excel number to date in Pandas DataFrame by using Python.
  • Here we can use an example of an excel number to do this task use a library called xlrd internally and this can be used for reading input files.
  • To install the xlrd package in Python you have to use the pip install xlrd command and this module allows the user to read data from an excel number or file.

Syntax:

Here is the Syntax of xldate_as_datetime

xlrd.xldate_as_datetime()

Source Code:

import xlrd

new_val = 42580
new_date = xlrd.xldate_as_datetime(new_val, 0)
Output = new_date.date()
print(Output)

After installing ‘xlrd’ package you have to import xlrd library in example and now use the xldate_as_datetime() method to convert an excel number into a DateTime object.

Here is the Output of the following given code

Convert excel number to date in Pandas
Convert excel number to date in Pandas

Read: Count Rows in Pandas DataFrame

Convert int column to datetime Pandas

  • Let us see how to convert integer columns to datetime by using Python Pandas.
  • In Python, if you want to convert a column to datetime then you can easily apply the pd.to_datetime() method. To perform this task first create a dataframe from the dictionary and then use the pd.dataframe class with the dictionary as input.
  • Now to convert integer column to datetime use the dataframe ‘df’ in brackets and within this bracket mention the column name which you want to convert with datetime.

Source Code:

import pandas as pd
new_dictionary = {'Increment':[7734, 1122, 5544, 1021, 1123],
       'emp_name': ['Micheal', 'William',
                   'George',
                   'John', 'Potter'],

       'Date':['10/19/2004', '02/23/1998', 
               '08/27/2011', '06/30/1993', '09/18/1992'],
       'int_Date': [19980602, 19940514, 20090225, 19920719,
                20170225]}

df = pd.DataFrame(new_dictionary)

print(df.head())
df['int_Date'] = pd.to_datetime(df['int_Date'])
print("Convert Column to Datetime:")
print(df)

Here is the Screenshot of the following given code

Convert int column to datetime Pandas
Convert int column to datetime Pandas

Read: Python Pandas DataFrame Iterrows

Pandas convert datetimeindex to integer

  • In this section, we will discuss how to convert datetimeindex with an integer in Pandas Dataframe by using Python.
  • By using the combination of pd.to_timedelta() and dt.total_seconds() method we can perform this particular task easily. In Pandas the timedelta format is used for the addition of the date and time components along with that the total_seconds() method is directly available on Timedeltaindex and timedelta values.

Syntax:

Here is the Syntax of Pandas.to_delta() method

Pandas.to_delta
               (
                arg,
                unit=None,
                errors='raise'
               )
  • It consists of few parameters
    • arg: This parameter specifies the data object to be converted with time delta.
    • unit: By default its value is None and the values are ‘Y’,’M’,’W’,’D’.
    • errors: In this example we will set the errors=’ignore’.

Example:

import pandas as pd

new_data = pd.DataFrame({'date': ['2007:08:09', '1993:05:06','2001:02:03'] })
new_data=pd.to_timedelta(new_data.date).dt.total_seconds().astype(int)
print("Convert datetimeindex to integer:")
print(new_data)

Here is the execution of the following given code

Pandas convert datetimeindex to integer
Pandas convert datetimeindex to integer

Read: Python convert DataFrame to list

Convert int to datetime in Pandas with nan

  • In this Program, we will discuss how to convert integers to datetime in Pandas DataFrame with nan value.
  • Here we can use the Pandas.to_datetime() method to perform this task. First, we have to import pandas and numpy library and then create a dictionary ‘my_dict’ that contains key-value pair. In this example, the key has been considered as column name and the list values as integers.
  • In the given list we have assigned some integer and nan values it. Now we want to convert the integer with datetime along with nan.

Source Code:

import pandas as pd
import numpy as np

my_dict = {'no_dates':  [19990320,np.nan,20200416,20010828,np.nan]}
df = pd.DataFrame(my_dict, columns = ['no_dates'])

df['no_dates'] = pd.to_datetime(df['no_dates'], format='%Y%m%d')

print (df)

You can refer to the below Screenshot

Convert int to datetime in Pandas with nan
Convert int to datetime in Pandas with nan

As you can see in the Screenshot the output is shown the nan values have been replaced with ‘NAT’.In Python, the NAT represents the missing values.

Read: Python Pandas Drop Rows

Convert int to datetime in Pandas without decimal

  • In this section, we will discuss how to convert integer to datetime in Pandas DataFrame.
  • We have already covered this topic in the beginning so you can better understand this example. In this example, we have applied the same method Pandas.to_datetime.

Example:

import pandas as pd

new_val = 20061225
new_result=pd.to_datetime(str(new_val), format='%Y%m%d')
print(new_result)

Here is the Screenshot of the following given code

Convert int to datetime in Pandas without decimal
Convert int to datetime in Pandas without decimal

Read: How to Convert Pandas DataFrame to a Dictionary

Convert int to datetime in Pandas string

  • In this Program, we will discuss how to convert integers to datetime in Pandas string.
  • By using the astype(str) method we can change the datatype of a series and this function also provides to convert the existing column to a different type.

Syntax:

Here is the Syntax of df.astype() method

DataFrame.astype
                (
                 dtype,
                 copy=True,
                 errors='raise'
                )
  • It consists of a few parameters.
    • dtype: This parameter specifies the conversion of series with integer or string.
    • copy: By default it takes ‘True’ value and makes a copy of dataframe.
    • errors: This parameter indicates if a datatype is invalid then the error ‘raise’.

Example:

import pandas as pd

new_val = 19960425
new_data = pd.DataFrame({'date':[new_val]*2})
new_data['New_Date'] = pd.to_datetime(new_data['date'].astype(str), format='%Y%m%d')
print(new_data)

Here is the execution of the following given code

Convert int to datetime in Pandas string
Convert int to datetime in Pandas string

You may also like to read the following tutorials.

In this Python tutorial, we have learned how to convert Integers to Datetime in Pandas DataFrame. Also, we have covered these topics.

  • Convert int to datetime in Pandas
  • Convert number to date in Pandas
  • Convert excel number to date in Pandas
  • Convert int column to datetime Pandas
  • Pandas convert datetimeindex to integer
  • Convert int to datetime in Pandas with nan
  • Convert int to datetime in Pandas without decimal
  • Convert int to datetime in Pandas string