晚上好,
我有一个数据框(Pandas),其中有一列代表日期,格式如下:
print(df["date"])
14/01/18 12:47
14/01/18 12:48
14/01/18 12:50
14/01/18 12:57
14/01/18 12:57
14/01/18 12:57
14/01/18 12:57
14/01/18 12:57
14/01/18 12:58
具体来说,我想: 1. 使用pd.to_datetime将其转换为日期时间 2. 创建以下附加列:
df["month"]
df["day"]
df["year"]
df["hour"]
df["minute"]
我尝试运行:
df['date'] = pd.to_datetime(df['date'], format = "%d/%m/%Y %H/%M" )
但是出现以下错误:
time data '02/01/18 08:41' does not match format '%d/%m/%Y %H/%M' (match)
最佳答案
除了grovina的答案......您可以直接使用dt
访问器,而不是使用apply。
这是一个示例:
>>> data = [['2017-12-01'], ['2017-12-30'],['2018-01-01']]
>>> df = pd.DataFrame(data=data, columns=['date'])
>>> df
date
0 2017-12-01
1 2017-12-30
2 2018-01-01
>>> df.date
0 2017-12-01
1 2017-12-30
2 2018-01-01
Name: date, dtype: object
注意 df.date 为何是一个对象?让我们把它变成你想要的日期
>>> df.date = pd.to_datetime(df.date)
>>> df.date
0 2017-12-01
1 2017-12-30
2 2018-01-01
Name: date, dtype: datetime64[ns]
您想要的格式是字符串格式。我认为您无法将实际的 datetime64 转换为看起来像该格式。现在,让我们在单独的列中制作日期的新格式字符串版本
>>> df['new_formatted_date'] = df.date.dt.strftime('%d/%m/%y %H:%M')
>>> df.new_formatted_date
0 01/12/17 00:00
1 30/12/17 00:00
2 01/01/18 00:00
Name: new_formatted_date, dtype: object
最后,由于 df.date 列现在的日期为 datetime64...您可以在其上使用 dt 访问器。无需使用apply
>>> df['month'] = df.date.dt.month
>>> df['day'] = df.date.dt.day
>>> df['year'] = df.date.dt.year
>>> df['hour'] = df.date.dt.hour
>>> df['minute'] = df.date.dt.minute
>>> df
date new_formatted_date month day year hour minute
0 2017-12-01 01/12/17 00:00 12 1 2017 0 0
1 2017-12-30 30/12/17 00:00 12 30 2017 0 0
2 2018-01-01 01/01/18 00:00 1 1 2018 0 0
关于python - pd.to_datetime 小时和秒,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48444373/