1

I have some data that is observed and registered by week, and I'm trying to plot this data with matplotlib. I'm currently using the date format yyyymmw, where w stands for the week of the month (can assume any value from 1 to 5). Every week starts on Tuesday and ends on Monday unless the end/start of the month cuts this week in two.

My question is: is there any datetime format that supports these types of dates?

Here's an example of the data:

+ --------+-------+------+
|   week  | Sugar | Soy  |
+ --------+-------+------+
| 2019121 | 534.3 | 49.1 |
| 2019122 | 423.6 | 45.2 |
+ --------+-------+------+
Das_Geek
  • 2,775
  • 7
  • 20
  • 26
olenscki
  • 487
  • 7
  • 22

2 Answers2

2

You can have a look at matplotlib's date tickers and formatters.

In essence, given an Axes object, say ax, you can set a locator for an axis, and then a formatter. For instance, you could use a WeekdayLocator to tick every Monday, and use a DateFormatter instanciated with "%y-%m-%W" to display each date as yyyy-mm-w.

Right leg
  • 16,080
  • 7
  • 48
  • 81
  • That would be the second (and easy) step. The first would need to be to convert your yyyymmw thing to a normal date. – ImportanceOfBeingErnest Jan 14 '20 at 13:12
  • @ImportanceOfBeingErnest Ah you're right, my bad. Well, I can't think of a straightforward way to do this off the top of my head, but I suppose `strptime` in combination with [something like this](https://stackoverflow.com/a/16804556/7051394) should help on that part. – Right leg Jan 14 '20 at 13:15
0

A little update since I have been able to overcome this. As @ImportanceOfBeingErnest pointed, there was no way to transform this format to a datetime format. So, I transformed every week on its first day using datetime and calendar. Calendar was really helpful. Here's my code:

from datetime import datetime
import calendar
def transform_week_into_days(week): #week example: '2018031'
    week = str(week)
    year = week[:4]
    month = week[4:6]
    week = week[6]
    month_year = year+'-'+month
    calendar = calendar.monthcalendar(int(ano), int(mes))
    week_start = []
    for i in range(len(calendar)):
        for j in range(len(calendar[-1])):
            if calendar[i][j] != 0:
                day = str(month_year)+'-'+str(var[i][j])
                datetime_object = datetime.strptime(day, '%Y-%m-%d')
                if datetime_object.weekday() != 5 and datetime_object.weekday() != 6: #check if the first day of week is saturday or sunday
                    week_start.append(day)
                break
    return week_start[int(week)-1]

Hope this can help whoever needs.

olenscki
  • 487
  • 7
  • 22