Warm tip: This article is reproduced from stackoverflow.com, please click
python

Python get week starting day from yearweek

发布于 2020-03-27 15:41:38

Recently I was bothered with the function that would return starting day of the week for a given string concatenation of year and week and surprisingly couldn't find it anywhere.

I saw similar ones (ie. question1, question2), but I am only given the year and week, without days.

Let's have an example input and a desired output:

func('202005') -> Monday 27.01.2020

I found a lot of counting, but not anything elegant, a smooth one-liner. Is there any?

Questioner
brian
Viewed
17
brian 2020-01-31 16:30

During investigation I combined some similar approaches with python docs regading datetime, so leaving my proposal here that I run with for any bypassers:

# 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")