繁体   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