user10784511
user10784511

Reputation:

How to convert the date to datetime

I have a date in the format as 1998-01-29 and i want to convert it to 01/29/1998 0:00 this format.

i have df

week  Year   
0   1998     
1   1998       
2   1998       
3   1998 

i converted week and year to date using the following code:

pd.to_datetime(df.Year.astype(str), format='%Y') + \
             pd.to_timedelta(df.week.mul(7).astype(str) + ' days')

but when i am using this code i am getting this in this format:

datetime
1998-3-10
1998-5-10

but i want the datetime to be converted to this format:

week  Year   datetime
0   1998     10/3/1998 0:00
1   1998     10/5/1998 0:00  
2   1998     10/7/1998 0:00  
3   1998     10/9/1998 0:00

i have used the following code but didnt get the desired results:

df['datetime'].astype('datetime64[ns]') 

How do i convert the date format?

Upvotes: 0

Views: 33

Answers (1)

jezrael
jezrael

Reputation: 863701

Is it possible by Series.dt.strftime, but datetimes are converted to strings:

df_keywordlist['datetime'] = df_keywordlist['datetime'].dt.strftime('%d/%m/%Y %H:%M')
print (df_keywordlist)
   week  Year          datetime
0     0  1998  01/01/1998 00:00
1     1  1998  08/01/1998 00:00
2     2  1998  15/01/1998 00:00
3     3  1998  22/01/1998 00:00

In python is default format of dates and datetimes and not possible change it.

Upvotes: 1

Related Questions