[英]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.