Peslier53
Peslier53

Reputation: 619

Pandas Datetime conversion

I have the following dataframe;

Date = ['01-Jan','01-Jan','01-Jan','01-Jan']                                                    
Heure = ['00:00','01:00','02:00','03:00']
value =[1,2,3,4]
df = pd.DataFrame({'value':value,'Date':Date,'Hour':Heure})  
print(df)

     Date   Hour  value
0  01-Jan  00:00      1
1  01-Jan  01:00      2
2  01-Jan  02:00      3
3  01-Jan  03:00      4

I am trying to create a datetime index, knowing that the file I am working with is for 2015. I have tried a lot of things but can get it to work! I tried to only convert the date and the month, but even that does not work:

df.index  = pd.to_datetime(df['Date'],format='%d-%m')

I expect the following result:

                      Date   Hour     value
2015-01-01 00:00:00  01-Jan  00:00      1
2015-01-01 01:00:00  01-Jan  01:00      2
2015-01-01 02:00:00  01-Jan  02:00      3
2015-01-01 03:00:00  01-Jan  03:00      4

Does anyone know how to do it?

Thanks,

Upvotes: 1

Views: 41

Answers (2)

BENY
BENY

Reputation: 323226

You can replace the default 1900 by using replace

s=pd.to_datetime(df['Date']+df['Hour'],format='%d-%b%H:%M').apply(lambda x : x.replace(year=2015))
s
Out[131]: 
0   2015-01-01 00:00:00
1   2015-01-01 01:00:00
2   2015-01-01 02:00:00
3   2015-01-01 03:00:00
dtype: datetime64[ns]

df.index=s

Upvotes: 0

sacuL
sacuL

Reputation: 51335

You need to explicitely add 2015 somehow, and include the Hour column as well. I would do something like this:

df.index = pd.to_datetime(df.Date + '-2015 ' + df.Hour, format='%d-%b-%Y %H:%M')

>>> df
                       Date   Hour  value
2015-01-01 00:00:00  01-Jan  00:00      1
2015-01-01 01:00:00  01-Jan  01:00      2
2015-01-01 02:00:00  01-Jan  02:00      3
2015-01-01 03:00:00  01-Jan  03:00      4

Upvotes: 1

Related Questions