Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datetime from year and week number

I have a year and a week number which I want to convert into a datetime.datetiem object. My (naive?) reading of the documentation hinted that strptime('2016 00', '%Y %W') should do just that. However:

In [2]: from datetime import datetime

In [3]: datetime.strptime('2016 00', '%Y %W')
Out[3]: datetime(2016, 1, 1, 0, 0)

In [4]: datetime.strptime('2016 52', '%Y %W')
Out[4]: datetime(2016, 1, 1, 0, 0)

What am I doing wrong?

like image 577
Sardathrion - against SE abuse Avatar asked Jul 22 '16 14:07

Sardathrion - against SE abuse


People also ask

How do I get the week number from a date in Python?

dt. isocalendar()[0] returns the year, dt. isocalendar()[1] returns the week number, dt. isocalendar()[2] returns the week day.

What is Isocalendar?

The calendar defined in the ISO standards 8601 is commonly referred to as the ISO calendar. The ISO calendar corresponds with the Gregorian (Western) calendar and uses the same year number, but its length is defined to be an integral number of weeks.


1 Answers

So it turns out that the week number isn't enough for strptime to get the date. Add a default day of the week to your string so it will work.

> from datetime import datetime
> myDate = "2016 51"
> datetime.strptime(myDate + ' 0', "%Y %W %w")
> datetime.datetime(2016, 12, 25, 0, 0)

The 0 tells it to pick the Sunday of that week, but you can change that in the range of 0 through 6 for each day.

like image 147
Peter Wang Avatar answered Oct 24 '22 06:10

Peter Wang