温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - Python get week starting day from yearweek

其他 - Python从年周开始从周开始

发布于 2020-03-27 15:53:50

最近,我不满意该函数会返回给定的年和周字符串连接的星期几开始的功能,并且令人惊讶地找不到它。

我看到了类似的内容(例如,question1question2),但是只给了我一年和一周,没有几天。

让我们有一个示例输入和所需的输出:

func('202005') -> Monday 27.01.2020

我发现很多东西都很光滑,但没有任何优雅。有没有?

查看更多

查看更多

提问者
brian
被浏览
14
brian 2020-01-31 16:30

在调查期间,我将一些类似的方法与python文档重新绑定了datetime结合在一起,因此将我的建议留给我使用,以供任何绕行者使用:

# python3.7

import datetime

def get_week_start_date(yearweek: str) -> datetime:
    """
    Return date of starting the week (Monday)
    i.e: 201944 returns datetime.datetime(2019, 11, 4, 0, 0)

    %G -> ISO 8601 year with century representing the year that contains the greater part of the ISO week (%V).
    %u -> ISO 8601 weekday as a decimal number where 1 is Monday.
    %V -> ISO 8601 week as a decimal number with Monday as the first day of the week. Week 01 is the week containing Jan 4.

    Arguments:
        yearweek {str} -- year to be calculated

    Returns:
        datetime -- Date of starting the week in passed year, week
    """
    return datetime.datetime.strptime(f"{yearweek}-1", "%G%V-%u")