问题
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?
回答1:
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.
回答2:
From the docs (see note 7 at the bottom):
When used with the
strptime()
method,%U
and%W
are only used in calculations when the day of the week and the year are specified.
Thus, as long as you don't specify the weekday, you will effectively get the same result as datetime.strptime('2016', '%Y')
.
来源:https://stackoverflow.com/questions/38528515/datetime-from-year-and-week-number