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.week
print(df)
print(df.dtypes)
结果如下:
date year month day week
0 -12-09 12 9 50
1 -12-02 12 2 49
date datetime64[ns]
year int64
month int64
day int64
week int64
dtype: 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 week
0 -12-09 -12-09 12 09 -12 49
1 -12-02 -12-02 12 02 -12 48
date datetime64[ns]
year-month-day object
year object
month object
day object
month-day object
week object
dtype: object
欢迎关注,一起学习
参考: