PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, December 19, 2022

[FIXED] How can I subtract two date time values in a Pandas Dataframe

 December 19, 2022     dataframe, datetime, pandas, python, syntax     No comments   

Issue

I’m working on a project and I need to subtract two date time values to get the number of days. A sample of the data can be seen below:


                   ALARM_DATE               CONT_DATE  \
0      2020/06/18 00:00:00+00  2020/06/23 00:00:00+00   
1      2020/06/01 00:00:00+00  2020/06/04 00:00:00+00   
2      2020/08/10 00:00:00+00  2020/03/01 00:00:00+00   
3      2020/03/31 00:00:00+00  2020/04/01 00:00:00+00   
4      2020/04/14 00:00:00+00  2020/04/19 00:00:00+00   
...                       ...                     ...   

I tried simply subtracting the values, but obviously that didn’t work. Can anyone please help?


Solution

Convert your columns to actual dates first:

df['ALARM_DATE'] = pd.to_datetime(df['ALARM_DATE'])
df['CONT_DATE'] = pd.to_datetime(df['CONT_DATE'])

Or:

df[['ALARM_DATE', 'CONT_DATE']] = df[['ALARM_DATE', 'CONT_DATE']].apply(pd.to_datetime)

Output:

>>> df['CONT_DATE'] - df['ALARM_DATE']
0      5 days
1      3 days
2   -162 days
3      1 days
4      5 days
dtype: timedelta64[ns]


Answered By - user17242583
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing