Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert yyyy-mm-dd to yyyy-ww in Python

Tags:

python

pandas

I'm trying to to convert yyyy-mm-dd into yyyy-ww.

How is this achieved for the following dataframe:

dates = {'date': ['2015-02-04','2016-03-05']}

df = pd.DataFrame(dates, columns=['date'])

print(df)
0   2015-02-04
1   2016-03-05
dtype: datetime64[ns]

I've tried using

YW = pd.to_datetime(df, format='%Y%W')

However without luck.

like image 685
Artem Avatar asked Mar 01 '26 08:03

Artem


1 Answers

Use to_datetime working with columns called year, month and day for datetimes and add Series.dt.strftime for custom format:

YW = pd.to_datetime(df).dt.strftime('%Y%W')
print (YW)
0    201505
1    201609
dtype: object

If possible another columns filter only necessary by list:

YW = pd.to_datetime(df[['year','month','day']]).dt.strftime('%Y%W')

EDIT:

YW = pd.to_datetime(df['date']).dt.strftime('%Y%W')
print (YW)
0    201505
1    201609
Name: date, dtype: object
like image 160
jezrael Avatar answered Mar 02 '26 22:03

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!