Date manipulation in Python

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

Date manipulation in Python
String date manipulation in Python
String manipulation in python
Get date in Python
Date calculation in python
Date calculation in Python
Sort by date in python
Pixel manipulation of images in Python
Python in optimization
CURL in python
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
Python date arithmetic
Python Grammar-String Manipulation
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
Python list manipulation
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Daily AtCoder # 36 in Python
Clustering text in Python
Implement Enigma in python
Daily AtCoder # 32 in Python
Daily AtCoder # 6 in Python
Daily AtCoder # 18 in Python
Edit fonts in Python
Singleton pattern in Python
File operations in Python