Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

One of the columns in my dataframe is a date column, how can I add a new column to the dataframe being the difference of today vs that date in days?

I have a bunch of dates in the following format

LastUpdated
2021-06-19 12:41:38
2021-06-20 15:09:05
2021-06-20 15:09:39
2021-06-28 08:59:29
2021-08-03 14:02:03

Last updated being the name of that column in my dataframe. How can I add an extra column to the dataframe which will be the difference in days between now and the date of each row?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I hope your LastUpdated column is already of type datetime64. If not, convert it using pd.to_datetime. That makes datetime calculation a lot easier. The trick to get the difference in days, hours, minutes, etc. is to divide the Timedelta object with pd.Timedelta(<unit>=1):

df["LastUpdated"] = pd.to_datetime(df["LastUpdated"])
df["Diff"] = (pd.Timestamp.now() - df["LastUpdated"]) / pd.Timedelta(days=1)

# If you want to strip out the time
df["Diff"] = (pd.Timestamp.now().normalize() - df["LastUpdated"].dt.normalize()) / pd.Timedelta(days=1)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading