在 Python 中将 yyyy-mm-dd 转换为 yyyy-ww [英] Convert yyyy-mm-dd to yyyy-ww in Python

查看:72
本文介绍了在 Python 中将 yyyy-mm-dd 转换为 yyyy-ww的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将 yyyy-mm-dd 转换为 yyyy-ww.

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]

我试过使用

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

不过运气不好.

推荐答案

使用 to_datetime 使用名为 yearmonthday 的列来处理日期时间和添加 Series.dt.strftime 自定义格式:

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')

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

这篇关于在 Python 中将 yyyy-mm-dd 转换为 yyyy-ww的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆