Generating Dates To The Days Of A Week In Python?
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, S
Solution 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
Solution 2:
You can set your initial date like this:
from datetime import datetime, timedeltad= 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)
Solution 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')
Post a Comment for "Generating Dates To The Days Of A Week In Python?"