【Python】时间函数


获取周次

# isocalendar 返回(年号,第几周,第几天)
def get_week(dt):
    all_df=dt.isocalendar()
    strs=str(all_df[0])+"_"+str(all_df[1])
    return strs
data_all['apply_week']=data_all['申请日'].apply(lambda x:get_week(x))
from datetime import datetime

dayOfWeek = datetime.now().isoweekday() ###返回数字1-7代表周一到周日
day_Week = datetime.now().weekday() ###返回从0开始的数字,比如今天是星期5,那么返回的就是4
print(dayOfWeek )
print(day_Week )

获取时间维度

# 日期类型
df['E1_B6_interval'] = (df.E1.astype('datetime64[ns]') - df.B6.astype('datetime64[ns]')).map(lambda x:x.days)
df['E1_is_month_end'] = pd.to_datetime(df.E1).map(lambda x :x.is_month_end) # 指示日期是否为每月的最后一天。
df['E1_dayofweek'] = df.E1.astype('datetime64[ns]').dt.dayofweek
df['B6_hour'] = df.B6.astype('datetime64[ns]').dt.hour
df.head()