首页 > 解决方案 > 如何在 Python 中解析年初至今的日期?

问题描述

我正在使用 %Y-%W 格式将 Python 中的日期转换为年-周格式。我希望能够使用相同的字符串从年周转换回日期,但我得到的是 1 月 1 日(Python 3.9.1)。

from datetime import datetime
datetime.strftime(datetime(2020,6,22), '%Y-%W')
# This returns 2020-25 
datetime.strptime('2020-25', '%Y-%W')
# This returns datetime.datetime(2020, 1, 1, 0, 0)

为什么会这样?进行转换的最佳方法是什么?

标签: python

解决方案


当我继续搜索时,在文档脚注中找到了答案。

当与 strptime() 方法一起使用时,%U 和 %W 仅在指定星期几和日历年 (%Y) 时用于计算。

https://python.readthedocs.io/en/latest/library/datetime.html#strftime-strptime-behavior

本来预计它会引发错误或返回与星期一相对应的日期,因为文档指定使用 %W 一周从星期一开始。

所以要解决这个问题,我们需要在字符串和格式中包含工作日。

datetime.strptime('2020-25-1', '%Y-%W-%w')
# returns datetime.datetime(2020, 6, 22, 0, 0)

推荐阅读