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?
dt. isocalendar()[0] returns the year, dt. isocalendar()[1] returns the week number, dt. isocalendar()[2] returns the week day.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With