【发布时间】:2021-04-01 03:47:54
【问题描述】:
关于如何将不同的时间戳格式转换为日期时间对象的例子有很多,但反过来几乎没有。
我的目标只是将 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')?应该有更简单的东西
【问题讨论】:
标签: python pandas datetime timestamp