1

In my scenario

start_date = 2020-02-11 11:47:38
end_date = 2020-04-25 09:26:15 

diff_date = end_date - start_date

print(diff_date)

output in console: 73 days, 21:38:37

writing in excel

worksheet.write(0,0, diff_date)

output in excel:74.9018171296296

Question is I want to get the same formate and type in excel as in console but It changes.

Note: str(diff_date) gives the same format but it changes the datetime object into string type.

rdas
  • 20,604
  • 6
  • 33
  • 46
Ali Mughal
  • 21
  • 4
  • instead of the solution shown at the link in my comment above, you could also do this by writing a formula to another Excel cell, e.g. `=INT(A1-B1) & " days, " & TEXT((B1-A1),"h"" hrs ""m"" mins """)`, assuming start and end date are at A1 and B1 in this example. – FObersteiner Apr 27 '20 at 09:23

1 Answers1

1
start_date = "2020-02-11 11:47:38"
end_date = "2020-04-25 09:26:15"
d1 = datetime.strptime(start_date, '%Y-%m-%d %H:%M:%S')
d2 = datetime.strptime(end_date, '%Y-%m-%d %H:%M:%S')
d = d2-d1
d

output is

datetime.timedelta(days=73, seconds=77917)

then

import pandas as pd
data_pd = pd.DataFrame(columns=['date_diff'])
data_pd.loc[1, ['date_diff']] = pd.to_timedelta(d).isoformat()
data_pd.to_excel('data_pd.xlsx', index = False)

when reading the file

new_data = pd.read_excel('data_pd.xlsx')
new_data_converted = pd.to_timedelta(new_data.date_diff)

Output is

Out[164]: 
0   73 days 21:38:37
Name: date_diff, dtype: timedelta64[ns]
Umer Javed
  • 11
  • 2