【问题标题】:Extract Year, Month and Day from datetime64[ns, UTC], Python [duplicate]从 datetime64 [ns, UTC],Python [重复] 中提取年、月和日
【发布时间】:2019-04-29 18:06:05
【问题描述】:
我在 df 中有这个专栏:
> df["time"]
0 2007-02-01 22:00:00+00:00
1 2007-02-01 22:00:00+00:00
2 2007-02-01 22:00:00+00:00
3 2007-02-01 22:00:00+00:00
4 2007-02-01 22:00:00+00:00
我想创建三个包含日、月和年的新列,但我想不出一种方法来提取 time column 中的每一个。
【问题讨论】:
标签:
python
pandas
datetime
time
datetime64
【解决方案1】:
为了不修改现有的time 列,请使用pd.to_datetime 创建一个单独的日期时间序列,然后使用dt 访问器:
# obtain datetime series:
datetimes = pd.to_datetime(df['time'])
# assign your new columns
df['day'] = datetimes.dt.day
df['month'] = datetimes.dt.month
df['year'] = datetimes.dt.year
>>> df
time day month year
0 2007-02-01 22:00:00+00:00 1 2 2007
1 2007-02-01 22:00:00+00:00 1 2 2007
2 2007-02-01 22:00:00+00:00 1 2 2007
3 2007-02-01 22:00:00+00:00 1 2 2007
4 2007-02-01 22:00:00+00:00 1 2 2007
另一种方法是在datetime.dt.date 系列上使用str.split('-'):
datetimes = pd.to_datetime(df['time'])
df[['year','month','day']] = datetimes.dt.date.astype(str).str.split('-',expand=True)
>>> df
time year month day
0 2007-02-01 22:00:00+00:00 2007 02 01
1 2007-02-01 22:00:00+00:00 2007 02 01
2 2007-02-01 22:00:00+00:00 2007 02 01
3 2007-02-01 22:00:00+00:00 2007 02 01
4 2007-02-01 22:00:00+00:00 2007 02 01