pandas入门: 时间字符串转换为年月日

pandas中时间字符串转换为年月日方法总结。

  • 创建一个dataframe
df = pd.DataFrame(['2019-12-09', '2019-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 2019-12-09  2019     12    9    50
1 2019-12-02  2019     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 2019-12-09     2019-12-09  2019    12  09   2019-12   49
1 2019-12-02     2019-12-02  2019    12  02   2019-12   48
date              datetime64[ns]
year-month-day            object
year                      object
month                     object
day                       object
month-day                 object
week                      object
dtype: object

参考:

https://www.cnblogs.com/bravesunforever/p/11219299.html
https://blog.csdn.net/jingjing_94/article/details/89195791

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值