Search code examples
pandasdataframebokehdatetime-formatpython-datetime

Datetime reformat weekly column


I split a dataframe from minute to daily, weekly and monthly. I had no problem to reformat the daily dataframe, though I am having a good bit of trouble trying to do the same with the weekly one. Here is the weekly dataframe if someone could help me out please, it would be great.
I am adding the code I used to reformat the daily dataframe, so it may helps!
I am plotting it with Bokeh and without the datetime format I won't be able to format the axis and hovertools as I would like.
Thanks beforehand.

dfDay1 = dfDay.loc['2014-01-01':'2020-09-31']
dfDay1 = dfDay1.reset_index()
dfDay1['date1'] = pd.to_datetime(dfDay1['date'], format=('%Y/%m/%d'))
dfDay1 = dfDay1.set_index('date')

That worked fine for the day format.


Solution

  • If need convert dates before / use Series.str.split with str[0], if dates after / use str[1]:

    df['date1'] = pd.to_datetime(df['week'].str.split('/').str[0])
    

    print (df)                          
                          week      Open     Low    High     Close     Volume  \
    0    2014-01-07/2014-01-13   58.1500   55.38   58.96   56.0000  324133239   
    1    2014-01-14/2014-01-20   56.3500   55.96   58.57   56.2500  141255151   
    2    2014-01-21/2014-01-27   57.8786   51.85   59.31   52.8600  279370121   
    3    2014-01-28/2014-02-03   53.7700   52.75   63.95   62.4900  447186604   
    4    2014-02-04/2014-02-10   62.8900   60.45   64.90   63.9100  238316161   
    ..                     ...       ...     ...     ...       ...        ...   
    347  2020-09-01/2020-09-07  297.4000  271.14  303.90  281.5962   98978386   
    348  2020-09-08/2020-09-14  275.0000  262.64  281.40  271.0100  109717114   
    349  2020-09-15/2020-09-21  272.6300  244.13  274.52  248.5800  123816172   
    350  2020-09-22/2020-09-28  254.3900  245.40  259.98  255.8800   98550687   
    351  2020-09-29/2020-10-05  258.2530  256.50  268.33  261.3500   81921670   
    
             date1  
    0   2014-01-07  
    1   2014-01-14  
    2   2014-01-21  
    3   2014-01-28  
    4   2014-02-04  
    ..         ...  
    347 2020-09-01  
    348 2020-09-08  
    349 2020-09-15  
    350 2020-09-22  
    351 2020-09-29  
    
    [352 rows x 7 columns]