-1

If I have two dates (ex. 19960104 and 19960314), what is the best way to get the number of days between these two dates? Actually I have to calculate many dates in my dataframe. I use the code:

`for j in range(datenumbers[i]):
    date_format = "%Y%m%d"
    a = datetime.strptime(str(df_first_day.date[j]), date_format)
    b = datetime.strptime(str(df_first_day.exdate[j]), date_format)
    delta = (b - a).days
    df_first_day.days_to_expire[j] = delta`

I need to put every difference between two dates in one of column of my dataframe. I wonder if there is a better way to do as not using for loop

夏明義
  • 11
  • 2

1 Answers1

0

You will find dates much easier to handle if you first convert text to datetime. Then it becomes trivial to compute a timedelta that answers your question.

import datetime as dt

fmt = '%Y%m%d'
d1 = dt.datetime.strptime('19960104', fmt)
d2 = dt.datetime.strptime('19960314', fmt)
print((d2 - d1).days)

This displays:

70

EDIT

If you choose to define a function:

def num_to_timestamp(ymd):
    return dt.datetime.strptime(str(num), '%Y%m%d')

then you can conveniently apply it to a column:

df['date'] = df['date'].apply(num_to_timestamp)

Similarly the axis=1 option lets you construct a column that is difference of two existing columns.

J_H
  • 17,926
  • 4
  • 24
  • 44
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. [From Review](https://stackoverflow.com/review/low-quality-posts/22615076) – double-beep Mar 30 '19 at 17:41
  • Thanks for your help! Actually I have to calculate many dates in my dataframe. I use the code: for j in range(datenumbers[i]): date_format = "%Y%m%d" a = datetime.strptime(str(df_first_day.date[j]), date_format) b = datetime.strptime(str(df_first_day.exdate[j]), date_format) delta = (b - a).days df_first_day.days_to_expire[j] = delta – 夏明義 Mar 31 '19 at 03:00
  • I need to put every difference between two dates in one of column of my dataframe. I wonder if there is a better way to do as not using for loop. – 夏明義 Mar 31 '19 at 03:04