简体   繁体   English

将年周至今的条件转换为该周中该月的最大天数的日期

[英]Convert year-week to date condition to date where the week has max days for that month

Let me explain, I'm trying to convert the 5th week of 2017; 让我解释一下,我正在尝试转换2017年的第5周; 201705 to a date that belongs to February because that belongs to 5th week of the year. 201705到属于2月的日期,因为它属于一年的第5周。

So far I've been able to convert the custom date format to a date as follows: 到目前为止,我已经能够将自定义日期格式转换为以下日期:

import datetime 
d = '201705'
dt = datetime.datetime.strptime(d+'1', '%Y%W%w')

Which then output, 2017-01-30 00:00:00 然后输出,2017-01-30 00:00:00

But is there a way I can convert the date to February and similarly all week numbers that belong to a month gets converted to that month 但是有一种方法可以将日期转换为2月,并且类似地,属于一个月的所有星期数都将转换为该月

EDIT: What I'm after is if the week number is 5 then its February, ,if its 9 then its March - sort of week-month mapping but I've not found any way of doing that besides changing the year-week to dateformat 编辑:我要的是,如果周数是5,然后是2月,如果周数是9,然后是3月-类似于周-月映射,但是除了将年-周更改为日期格式

import datetime 
d = '201705'
dt = datetime.datetime.strptime(d+'1', '%Y%W%w')
month_from_date = dt.strftime("%B")
print(dt)
print(month_from_date)

Will output: 将输出:

2017-01-30 00:00:00
January

I'm a bit confused as to why you are expecting February however, because 01-30 is, in fact, January. 对于您为什么期望2月,我有点困惑,因为01-30实际上是1月。

You can find more formatting info here 您可以在此处找到更多格式信息

A quick test of my comment, about choosing Sunday as the arbitrary week day rather than Monday. 快速测试一下我的评论,关于选择星期日作为任意工作日而不是星期一。

>>> import datetime
>>> d1=['201205','201305','201605','201705','201805','201905','202005','202105','202205','202305']
>>> d2=['201209','201309','201609','201709','201809','201909','202009','202109','202209','202309']
>>> for dat in d1:
...  datetime.datetime.strptime(dat+ '0','%Y%W%w')
... 
datetime.datetime(2012, 2, 5, 0, 0)
datetime.datetime(2013, 2, 10, 0, 0)
datetime.datetime(2016, 2, 7, 0, 0)
datetime.datetime(2017, 2, 5, 0, 0)
datetime.datetime(2018, 2, 4, 0, 0)
datetime.datetime(2019, 2, 10, 0, 0)
datetime.datetime(2020, 2, 9, 0, 0)
datetime.datetime(2021, 2, 7, 0, 0)
datetime.datetime(2022, 2, 6, 0, 0)
datetime.datetime(2023, 2, 5, 0, 0)
>>> for dat in d2:
...  datetime.datetime.strptime(dat+ '0','%Y%W%w')
... 
datetime.datetime(2012, 3, 4, 0, 0)
datetime.datetime(2013, 3, 10, 0, 0)
datetime.datetime(2016, 3, 6, 0, 0)                                            
datetime.datetime(2017, 3, 5, 0, 0)
datetime.datetime(2018, 3, 4, 0, 0)
datetime.datetime(2019, 3, 10, 0, 0)
datetime.datetime(2020, 3, 8, 0, 0)
datetime.datetime(2021, 3, 7, 0, 0)
datetime.datetime(2022, 3, 6, 0, 0)
datetime.datetime(2023, 3, 5, 0, 0)
>>> 

Your mileage may vary. 你的旅费可能会改变。
I haven't tested for weeks further into the year. 一年以后,我还没有进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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