简体   繁体   中英

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; 201705 to a date that belongs to February because that belongs to 5th week of the year.

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

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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