首页 > 解决方案 > 大熊猫时间戳的日期

问题描述

有很多关于如何将不同的时间戳格式转换为日期时间对象的例子,但几乎没有相反的例子。

我的目标只是将 datetime 日期转换为时间戳(即包括小时、分钟和秒的 00:00:00),我假设必须首先将小时、分钟和秒添加到 datetime 对象,然后可以转换为字符串。我的数据框如下所示:

data.head()
start_date  end_date
0   2013-01-10  2013-01-10
1   2013-01-26  2013-01-26
2   2013-01-26  2013-01-26
3   2013-01-26  2013-01-26
4   2013-02-13  2013-02-13


data.dtypes
start_date    object
end_date      object
dtype: object

我尝试过结合pandas.Timestamp()astype(str)但这不会返回所需的结果。

#this returns the right timestamp
pd.Timestamp(data['start_date'][0])
Timestamp('2013-01-10 00:00:00')

#H:M:S disappears 
data['start_date'] = data.apply(lambda row : pd.Timestamp(row['start_date']), axis = 1)
data['start_date'].astype(str)
0      2013-01-10
1      2013-01-26
2      2013-01-26
3      2013-01-26
4      2013-02-13

pandas 中将日期转换为看起来像 '2013-01-10 00:00:00' 的字符串的正确方法是什么(不将日期转换为字符串然后添加 + '00:00:00')?应该有更简单的东西

标签: pythonpandasdatetimetimestamp

解决方案


我们可以做的strftime

df=df.apply(pd.to_datetime)
print(df.start_date.dt.strftime('%Y-%m-%d %H:%M:%S'))
0    2013-01-10 00:00:00
1    2013-01-26 00:00:00
2    2013-01-26 00:00:00
3    2013-01-26 00:00:00
4    2013-02-13 00:00:00
Name: start_date, dtype: object

推荐阅读