pandas中时间字符串转换为年月日方法总结。
创建一个dataframe
df = pd.DataFrame(['-12-09', '-12-02'], columns=["date"])
方法1:先转换为时间类型,在获取年月日
# 转换为时间类型df["date"] = pd.to_datetime(df["date"], format='%Y-%m-%d')# 获取年df["year"] = pd.to_datetime(df["date"]).dt.year# 获取月df["month"] = pd.to_datetime(df["date"]).dt.month# 获取日df["day"] = pd.to_datetime(df["date"]).dt.day# 获取周df["week"] = pd.to_datetime(df["date"]).dt.weekprint(df)print(df.dtypes)
结果如下:
date year month day week0 -12-09 12 9 501 -12-02 12 2 49datedatetime64[ns]year int64month int64dayint64week int64dtype: object
方法2
# 转换为时间df["date"] = pd.to_datetime(df["date"])# 获取年月日df["year-month-day"] = df["date"].apply(lambda x: x.strftime("%Y-%m-%d"))# 获取年df["year"] = df["date"].apply(lambda x: x.strftime("%Y"))# 获取月df["month"] = df["date"].apply(lambda x: x.strftime("%m"))# 获取日df["day"] = df["date"].apply(lambda x: x.strftime("%d"))# 获取月日df["month-day"] = df["date"].apply(lambda x: x.strftime("%Y-%m"))# 获取周df['week'] = df['date'].apply(lambda x: x.strftime('%W'))print(df)print(df.dtypes)
结果如下:
date year-month-day year month day month-day week0 -12-09-12-09 12 09 -12 491 -12-02-12-02 12 02 -12 48date datetime64[ns]year-month-day objectyear objectmonth objectday objectmonth-day objectweek objectdtype: object
参考:
/bravesunforever/p/11219299.html/jingjing_94/article/details/89195791