TypeError: an integer is required (got type Timestamp)

10,747

The datetime module is part of the Python standard library. The constructor of the datetime.datetime class takes a specific year, month and day as parameter (Reference). You would invoke it e.g. with datetime.datetime(2020, 3, 8).

In your code you are querying a specific cell from a an Excel table via the pandas library. This cell happens to contain a date, which pandas detects and turns into a pandas.Timestamp object. The pandas library is not part of the Python standard library, for this reason Python's datetime class does not know about pandas.Timestamp. When you pass a pandas.Timestamp to the datetime constructor, you get the error message TypeError: an integer is required (got type Timestamp). This means datetime expected an integer (specifying the year), but received a pandas.Timestamp, which it does not understand.

However, pandas does know about datetime and offers you a helper function to_pydatetime to turn a pandas.Timestamp into a datetime object (reference). In your code, replace the assignment for f with:

    f=h.to_pydatetime().date()

The to_pydatetime() gives you a datetime.datetime object, and then the .date() turns it into a datetime.date object, which is required for the d=b-f in the next line, as you assigned b with datetime.date.today().

Alternatively, you could also change the declaration of b to b=dt.datetime.now() and then the assignment of f to f=h.to_pydatetime(). This would give you the precise time difference, not just the difference in days.

Share:
10,747
Admin
Author by

Admin

Updated on June 18, 2022

Comments

  • Admin
    Admin almost 2 years

    I have an Excel table in the following format:

    enter image description here

    I want to read this table with Python using the pandas modules and calculate the difference between an issue date and the current date. This is my current code:

        import pandas as pd
        import datetime as dt
        def abc():
            a=pd.read_excel('date time.xlsx')
            b=dt.date.today()
            print(b)
            c=(a['date of issue'])
            h=(c[0])
            f=dt.datetime(h)
            d=b-f
            print(d)
       abc()
    

    It is showing an error in line 7 (f=dt.datetime(h)). It reads TypeError: an integer is required (got type Timestamp).