Amelio Vazquez-Reina
Amelio Vazquez-Reina

Reputation: 96448

Converting week numbers to dates

Say I have a week number of a given year (e.g. week number 6 of 2014).

How can I convert this to the date of the Monday that starts that week?

One brute force solution I thought of would be to go through all Mondays of the year:

date1 = datetime.date(1,1,2014)
date2 = datetime.date(12,31,2014)
def monday_range(date1,date2):
    while date1 < date2:
        if date1.weekday() == 0:
            yield date1
        date1 = date1 + timedelta(days=1)

and store a hash from the first to the last Monday of the year, but this wouldn't do it, since, the first week of the year may not contain a Monday.

Upvotes: 7

Views: 16576

Answers (5)

Chris
Chris

Reputation: 45

To piggyback and give a different version of the answer @anon582847382 gave, you can do something like the below code if you're creating a function for it and the week number is given like "11-2023":

import time
from datetime import datetime

def get_date_from_week_number(str_value):
    temp_str = time.asctime(time.strptime('{} {} 1'.format(str_value[3:7], str_value[0:2]), '%Y %W %w'))
    return datetime.strptime(temp_str, '%a %b %d %H:%M:%S %Y').date()

Upvotes: 0

dimosbele
dimosbele

Reputation: 381

We can just add the number of weeks to the first day of the year.

>>> import datetime
>>> from dateutil.relativedelta import relativedelta

>>> week = 40
>>> year = 2019
>>> date = datetime.date(year,1,1)+relativedelta(weeks=+week)
>>> date
datetime.date(2019, 10, 8)

Upvotes: 0

anon582847382
anon582847382

Reputation: 20391

You could just feed the data into time.asctime().

>>> import time
>>> week = 6
>>> year = 2014
>>> atime = time.asctime(time.strptime('{} {} 1'.format(year, week), '%Y %W %w'))
>>> atime
'Mon Feb 10 00:00:00 2014'

EDIT: To convert this to a datetime.date object:

>>> datetime.datetime.fromtimestamp(time.mktime(atime)).date()
datetime.date(2014, 2, 10)

Upvotes: 6

ModusPwnins
ModusPwnins

Reputation: 156

A simple function to get the Monday, given a date.

def get_monday(dte):
    return dte - datetime.timedelta(days = dte.weekday())

Some sample output:

>>> get_monday(date1)
datetime.date(2013, 12, 30)
>>> get_monday(date2)
datetime.date(2014, 12, 29)

Call this function within your loop.

Upvotes: 5

Malcolm Murdoch
Malcolm Murdoch

Reputation: 1085

All about strptime \ strftime:

https://docs.python.org/2/library/datetime.html

mytime.strftime('%U') #for W\C Monday
mytime.strftime('%W') #for W\C Sunday

Sorry wrong way around

from datetime import datetime
mytime=datetime.strptime('2012W6 MON'. '%YW%U %a')

Strptime needs to see both the year and the weekday to do this. I'm assuming you've got weekly data so just add 'mon' to the end of the string. Enjoy

Upvotes: 6

Related Questions