如何将日期转换为日期时间

问题描述 投票:0回答:1

我有一个格式为1998-01-29的日期,我想将它转换为01/29/1998 0:00这种格式。

我有df

week  Year   
0   1998     
1   1998       
2   1998       
3   1998 

我使用以下代码将周和年转换为日期:

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

但是当我使用这个代码时,我会以这种格式得到这个:

datetime
1998-3-10
1998-5-10

但我希望将datetime转换为这种格式:

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

我使用了以下代码但没有得到预期的结果:

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

我如何转换日期格式?

python-3.x pandas
1个回答
1
投票

是否可以通过Series.dt.strftime,但日期时间转换为字符串:

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

在python中是日期和日期时间的默认格式,不可能更改它。

© www.soinside.com 2019 - 2024. All rights reserved.