Python复制闰年中周数转换的日期值

2024-10-02 16:33:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个dataframe,其中日期列的格式是format='%Y-W%W-%w'。我正在使用pd.to_datetime(urldict[key]['date']+'-1', format='%Y-W%W-%w')2018-W01等转换为实际日期,但由于闰年的原因,2020/2021年的数据似乎发生了错误的移动

随后,它为01-04-2021创建两个条目,第一个条目是2020-W53。返回的数据也未对齐

我不确定如何解决这个问题,因为我假设datetime库会解决这个问题

转换前:

date    region  total
2020-W51    africa  1
2020-W52    africa  2
2020-W53    africa  3
2021-W01    africa  4

转换后:

date    region  total
12/21/2020  africa  1
12/28/2020  africa  2
1/4/2021    africa  3
1/4/2021    africa  4

Tags: to数据formatdataframedatetimedate格式条目
1条回答
网友
1楼 · 发布于 2024-10-02 16:33:55

似乎您需要ISO 8601年/周/工作日,因此正确的格式化指令应该是'%G-W%V-%u'(请参见the docs,该部分的末尾)。为了

df

date  region  total
0  2020-W51  africa      1
1  2020-W52  africa      2
2  2020-W53  africa      3
3  2021-W01  africa      4

那看起来像

pd.to_datetime(df['date']+'-1', format='%G-W%V-%w')

0   2020-12-14
1   2020-12-21
2   2020-12-28
3   2021-01-04
Name: date, dtype: datetime64[ns]

相关:Python - Get date from day of week, year, and week number

相关问题 更多 >