需要使用的主要有两个工具包:
from datetime import datetime
from calendar import monthrange
分别计算当前的日期对应的:
- 所在年份
- 所在月份
- 当前月的第几日
- 星期几
- 当月的天数
- 当年的第几周
- 当月的第几周
完整示例代码
使用如下代码即可:
import pandas as pd
from math import ceil
from datetime import datetime
from calendar import monthrange
def week_of_month(dt, start_date=0):
"""获取当月的第几周"""
first_day = dt.replace(day=1) # 本月第一天
adjusted_dom = dt.day + (first_day.weekday() + start_date) % 7
return int(ceil(adjusted_dom / 7.0))
def load_trading_day(datetime_list):
trading_day_df = pd.DataFrame(index=datetime_list)
trading_day_df["year"] = [i.year for i in datetime_list] # 年份
trading_day_df['month'] = [i.month for i in datetime_list] # 月
trading_day_df['day'] = [i.day for i in datetime_list] # 当前月的第几日
trading_day_df['week'] = [i.weekday() for i in datetime_list] # 星期几,0是星期一
trading_day_df['max_date_of_month'] = [monthrange(i.year, i.month)[1] for i in datetime_list] # 当月的天数
trading_day_df['week_of_year'] = [i.isocalendar()[1] for i in datetime_list] # 当年的第几周
trading_day_df['week_of_month'] = [week_of_month(i) for i in datetime_list] # 当月的第几周
trading_day_df = trading_day_df.sort_index()
return trading_day_df
def main():
datetime_string = [i.strftime("%Y-%m-%d") for i in pd.date_range("2022-10-01", periods=400)]
datetime_list = [datetime.strptime(i, "%Y-%m-%d") for i in datetime_string]
print(load_trading_day(datetime_list))
if __name__ == '__main__':
main()