Python Forum

Full Version: How to subtract columns with dates?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi everyone, I have the code below that first creates a column with today's date (works) then I subtract an existing column but I get a TypeError. I ran the Dtype function and found that the excl.test column is being returned as an object (string), how can I convert this field into a date? Note, the excl.Date column is formatted as a date yyy-mm-dd.

from datetime import date

excl['test'] = (today)
print(excl.test - excl.Date)
There's no way this code can run without error as presented.
Please present full code, or at least working snippet.
This is my first set of code that runs without error.


import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from datetime import date


#Read excel file
excl = pd.read_excel (r'C:\Users\Family\Desktop\Anaconda\Book1.xlsx')

#Create new column w/data
excl['new_pop'] = (excl.Pop2010 + excl.Pop2020)

#Create a new column/flag

excl['new'] = pd.cut(excl.Pop2010, [0, 89, 90, 180, 365, 500, 750, 900, 1000], right = False)

#Create new excel file with old and new data

print(excl)

excl.to_excel("mastfile.xlsx")
This is my second block which I get errors on.

excl['test'] = (today)
print(excl.test - excl.Date)
The code below got it to work.

from datetime import date

excl['testdate'] = pd.to_datetime(excl['testdate'])

print(excl.testdate - excl.Date)