python - 大熊猫时间戳的日期
问题描述
有很多关于如何将不同的时间戳格式转换为日期时间对象的例子,但几乎没有相反的例子。
我的目标只是将 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'
)?应该有更简单的东西
解决方案
我们可以做的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
推荐阅读
- c# - 没有装饰器的反序列化
- statistics - 推荐的 Gap 统计模拟参考数据集数量
- excel - 在 Outlook vba 中打开 Excel 工作簿时出现不匹配错误
- swift - 为什么这不打开导航控制器窗口?
- java - 在 Java 9+ 中启动 jstatd
- python - 如何在boto3中获取过滤后的objectsCollection的大小
- jquery - jQuery调整对话框大小移动其边框
- python - 我可以使用 Django 模型对数据库执行复杂的查询吗?
- sql - MS Access Select 有效,但更新无效
- java - 使用元素 BufferedReader 和 BufferedWriter 创建数组对象