大熊猫时间戳的日期

时间:2021-04-01 03:47:54

标签: python pandas datetime timestamp

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

我的目标只是将 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')?应该有更简单的东西

1 个答案:

答案 0 :(得分:2)

我们可以做到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