【问题标题】:Dates to timestamp in pandas大熊猫时间戳的日期
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

    • 为什么是apply?熊猫的日期时间没有isoformat 方法吗?
    猜你喜欢
    • 2017-02-23
    • 2019-06-16
    • 1970-01-01
    • 2021-05-08
    • 1970-01-01
    • 2015-05-25
    • 2014-02-11
    相关资源
    最近更新 更多