-1

I want to convert string to date like this example

import datetime


str_date = "2021-m1-w3"
_date = datetime.datetime.strptime(str_date, "%Y-m%m-w%w")

What i want is first date of 3th week in January,2021.

datetime.datetime(2021, 2, 15, 0, 0)

But the result is:

datetime.datetime(2021, 1, 1, 0, 0)

How to get date by week number of month?

martineau
  • 119,623
  • 25
  • 170
  • 301
NgoDucHan
  • 11
  • 6
  • 1
    Does this answer your question? [Get date from week number](https://stackoverflow.com/questions/17087314/get-date-from-week-number) – kwkt Jan 15 '21 at 07:19

2 Answers2

0

You want %W with a capital W, not %w with a lowercase w, and to add the day of week:

str_date = "2021-m1-w3"
_date = datetime.datetime.strptime(str_date + "-0","%Y-m%m-w%W-%w") # starts from the first full week of the month
goalie1998
  • 1,427
  • 1
  • 9
  • 16
0

What i want is first date of 3rd week in January, 2021.

Provided that your string is of the format 2021-m1-w3 you could first parse the year, month ad week and then you can create a datetime.datetime that holds the first day of the month of the year you want (of the data you parsed) and you can add a datetime.timedelta(weeks=weeks) to it.

Parsing it is quite straightforward, you just have to split - and remove the m and w characters.

year, month, weeks = [int(item.replace("m", "").replace("w", "")) for item in str_date.split("-")]

Then you can create the object and add it with the weeks

DATE = datetime.datetime(year=year, month=month,day=1)
DATE + datetime.timedelta(weeks=weeks-1) # -1 because it is the start

The output is datetime.datetime(2021, 1, 15, 0, 0) which is the first day of week 3 of January 2021

Countour-Integral
  • 1,138
  • 2
  • 7
  • 21
  • This is not always true. What if the first week does not start with 1st? like for example the first monday of the month is on 3rd. 1st is already taken by the month before, therefore not counted as the first week. Or even if it was considered first week, the 22nd in your case, is not on monday/sunday in this scenario, so it's not the first day of the week either. – darkash Jan 15 '21 at 07:42
  • @darkash A week is 7 days, it does not matter wheter it starts on Monday or on Tuesday. The nth week of the month would be the `1st` of the month + n weeks (provided that n is small enough so the month does not change) . It could fall on any day why does that matter? – Countour-Integral Jan 15 '21 at 07:53