I wanted to get all the dates of the x days of the week in a certain month, or calculate the number of years and months after n months of a certain month, so I looked it up. I didn't know, but it seems that timedelta cannot calculate the month.
>>> from datetime import datetime
>>> import calendar
>>> now = datetime.strptime('2014-11-1', '%Y-%m-%d')
datetime.datetime(2014, 11, 1, 0, 0)
>>> #Get a list of Sunday dates for any month
>>> [x[calendar.SUNDAY] for x in calendar.monthcalendar(now.year, now.month)]
[2, 9, 16, 23, 30]
>>> #If the day of the week is only 4 times a month, the first value of the list will be 0.
>>> [x[calendar.MONDAY] for x in calendar.monthcalendar(now.year, now.month)]
[0, 3, 10, 17, 24]
>>> #Month calculation(Can calculate n months before and n months after the current date)
>>> import time
>>> datetime.fromtimestamp(time.mktime((now.year,now.month + 2,1,0,0,0,0,0,0)))
datetime.datetime(2015, 1, 1, 0, 0)
>>> datetime.fromtimestamp(time.mktime((now.year,now.month + 15,1,0,0,0,0,0,0)))
datetime.datetime(2016, 2, 1, 0, 0)
>>> #It's easy to calculate the date using timedelta
>>> from datetime import timedelta
>>> now + timedelta(days=1)
datetime.datetime(2014, 11, 2, 0, 0)
Reference link Date-related processing in Python Can't add / subtract months? 8.1. datetime — basic date and time types
Recommended Posts