Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 989
Amelio Vazquez-Reina Avatar asked Apr 01 '14 14:04

Amelio Vazquez-Reina


3 Answers

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)
like image 79
anon582847382 Avatar answered Sep 19 '22 18:09

anon582847382


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

like image 30
Malcolm Murdoch Avatar answered Sep 18 '22 18:09

Malcolm Murdoch


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.

like image 29
Edwin S. Avatar answered Sep 20 '22 18:09

Edwin S.