用python获取任意一个月的天数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from calendar import monthrange
import pandas as pd

#========================================================
# case1
#========================================================

year = 2021
month = 1
mr = monthrange(year, month)[1]
print(mr)

#========================================================
# case2
#========================================================

data = pd.Series(['2019-08-20', '2020-06-21', '2021-04-25', '2020-03-15'])
df = pd.DataFrame(data, columns = ['date'])
# 格式转换
df['date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')

df['mr'] = df['date'].apply(lambda x: monthrange(x.year, x.month)[1])
print(df['mr'])