Generating dates to the days of a week in Python?

2020-05-01 22:51发布

问题:

I need to generate a date of Monday of a week from a date (example: 2015/10/22). And generate the dates for the next days: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday.

Example in Java: (initial date = 2015/10/22)

// Monday:

date.set (Calendar.DAY_OF_WEEK, Calendar.MONDAY);

// Add the next day (Tuesday)

date.add (Calendar.DATE, 1);

// Add the next day (Wednesday):

date.add (Calendar.DATE, 1);

How can I do this in Python?

回答1:

Its easier in python using timedelta function

import datetime

mydate = datetime.datetime(2015, 10, 22, 00, 00, 00, 00)
mymondaydate = mydate - datetime.timedelta(days=mydate.weekday())
mytuesdaydate = mymondaydate + datetime.timedelta(days=1)

print(mydate)
print(mymondaydate)
print(mytuesdaydate)

The trick is the use of weekday() function. From documentation

date.weekday() - Return the day of the week as an integer, where Monday is 0 and Sunday is 6.

So subtracting it from current date gives the date of Monday of that week



回答2:

You can set your initial date like this:

from datetime import datetime, timedelta    
d = datetime(2015,10,22)

Then if you want to get the next monday, use timedelta and datetime.weekday() (Monday is 0):

d + timedelta(7 - d.weekday())
datetime.datetime(2015, 10, 26, 0, 0)


回答3:

Provide another version for your question. You can refer the document of official site: datetime, time

from datetime import date
from datetime import timedelta
import time

t = time.strptime('2015/10/22', '%Y/%m/%d')
old_day = date.fromtimestamp(time.mktime(t))
a_day = timedelta(days=1)
new_day = old_day + a_day

print new_day.strftime('%a')