Python Forum
How to subtract columns with dates?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to subtract columns with dates?
#1
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)
Reply
#2
There's no way this code can run without error as presented.
Please present full code, or at least working snippet.
Reply
#3
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)
Reply
#4
The code below got it to work.

from datetime import date

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

print(excl.testdate - excl.Date)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Fastest way to subtract elements of datasets of HDF5 file? Robotguy 3 2,663 Aug-01-2020, 11:48 PM
Last Post: scidam
  Groupby in pandas with conditional - add and subtract rregorr 2 6,987 Jul-12-2019, 05:17 PM
Last Post: rregorr
  Subtract rows (like r[1]-r[2] and r[3]-r[3]) and no pandas pradeepkumarbe 1 2,609 Dec-18-2018, 01:16 PM
Last Post: ichabod801

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020