简体   繁体   中英

Python get week starting day from yearweek

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?

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

time.strptime accepts %U in format string , which mean 2-digit number of week, however it requires day of week to work and starts counting weeks at 0 , that is

import time
yearweek = '202005'
yearweekmonday = yearweek+'1'
print(time.strptime(yearweekmonday, '%Y%U%w'))

Output: time.struct_time(tm_year=2020, tm_mon=2, tm_mday=3, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=34, tm_isdst=-1)

As weeks numbers starts with 0, 202005 result in 2020-02-03 rather than 2020-01-27 , but after you conver time.struct_time to datatime object from that you should be able to easily manipulate using timedelta .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM