簡體   English   中英

Python 從 yearweek 開始獲取周

[英]Python get week starting day from yearweek

最近我被一個函數所困擾,該函數會為給定的年份和星期的字符串連接返回一周的起始日,但令人驚訝的是在任何地方都找不到它。

我看到了類似的(即question1question2 ),但我只給出了年和周,沒有天。

讓我們有一個示例輸入和一個所需的輸出:

func('202005') -> Monday 27.01.2020

我發現了很多計數,但沒有任何優雅的東西,光滑的單線。 有沒有?

在調查期間,我將一些類似的方法與有關日期時間的 python 文檔結合起來,因此將我的建議留在這里,我可以為任何繞過者運行:

# 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接受格式 string 的%U ,這意味着 2 位數的周數,但是它需要星期幾才能工作並從0開始計算周數,即

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

輸出: 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)

由於周數從0開始, 202005的結果在2020-02-03 ,而不是2020-01-27 ,但之后你CONVER time.struct_timedatatime從您應該能夠很容易地使用操作對象timedelta

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM