简体   繁体   中英

how to create start and end date in dataframe

Product component lead time
mobile  batteries  2days
mobile  charger    4 days
charger cable      2 days
charger adapter     2 days

I want to create a start date and the due date for example adapter start date should be started by today and due date =start date+ lead time. for product mobile and component charger's start date is equal to the due date of the charger cable how can I implement this logic in python

The approach would be to use the pandas and datetime module and increment the number of days from the lead time column. But to use the number of days as a number, one would have to extract it out from the string (by removing the 'days', removing all whitespaces and converting the resultant to integer). Following is the implementation in code!

import pandas as pd
import datetime

d = {
    "Product":['mobile', 'mobile', 'charger', 'charger'],
     "component":['batteries', 'charger', 'cable', 'adapter'],
     "lead time":['2days', '4 days', '2 days', '2 days'] 
}
df = pd.DataFrame(data=d)
df['start date'] = datetime.datetime.now().date()
df['due date'] = ''
for i in range(0,len(df)):
  n = int(((df['lead time'][i]).replace("days","")).strip())
  df['due date'][i] = datetime.datetime.now().date()+datetime.timedelta(days=n)

The resulting dataframe would be -

    Product component   lead time   start date  due date
0   mobile  batteries   2days       2021-03-12  2021-03-14
1   mobile  charger     4 days      2021-03-12  2021-03-16
2   charger cable       2 days      2021-03-12  2021-03-14
3   charger adapter     2 days      2021-03-12  2021-03-14

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM