在熊猫中将包含年和周数的字符串转换为日期时间

时间:2019-01-18 09:47:05

标签: python pandas strftime string-to-datetime

我在Pandas数据框中有一列,其中以一种字符串的形式包含年份和星期数(1到52),格式为“ 2017_03”(表示2017年的3d周)。

我想将列转换为日期时间,并且正在使用pd.to_datetime()函数。但是我得到一个例外:

pd.to_datetime('2017_01',format = '%Y_%W')
ValueError: Cannot use '%W' or '%U' without day and year

另一方面,strftime文档提到:

enter image description here

我不确定自己在做什么错。

1 个答案:

答案 0 :(得分:2)

您还需要定义start day

a = pd.to_datetime('2017_01_0',format = '%Y_%W_%w')
print (a)
2017-01-08 00:00:00

a = pd.to_datetime('2017_01_1',format = '%Y_%W_%w')
print (a)
2017-01-02 00:00:00

a = pd.to_datetime('2017_01_2',format = '%Y_%W_%w')
print (a)
2017-01-03 00:00:00