python - 如何在 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)
为什么会这样?进行转换的最佳方法是什么?
解决方案
当我继续搜索时,在文档脚注中找到了答案。
当与 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)
推荐阅读
- c# - 如何在运行时读取给定项目中的 MSBuild 属性?
- docker - 如何在 Windows 中找到 Docker 容器可用的地址?
- c# - PDF中的段落阅读
- javascript - 我的工作代码中有错误。它不能正常工作
- mobile - Appium_Error : 返回值无法使用 Xcode 10.0 转换为 WebElement
- javascript - 有没有办法在浏览器窗口之外跟踪鼠标事件?
- python - 如何在具有多处理的无限循环中发出请求
- angular - 在 mat-dialog 中显示 mat-table
- c++ - C++ 的双冒号在类名而不是命名空间之后使用
- typescript - 如何从打字稿集合中合并字典?