[英]Python get week starting day from yearweek
在調查期間,我將一些類似的方法與有關日期時間的 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_time
以datatime
從您應該能夠很容易地使用操作對象timedelta
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.