【问题标题】:Given a timestamp, get total N. of seconds in the hour给定一个时间戳,得到一小时内的总秒数
【发布时间】:2015-11-28 15:34:38
【问题描述】:

给定一个 Pandas 时间戳:

> pd.Timestamp.now()
  Timestamp('2015-09-02 19:33:55.714410')

如何获得一小时内的分钟数(或秒数或微秒数)? (作为总数的小数部分)。请注意,我并不是在询问已经过去了多少 完整 分钟(或秒或微秒)。

【问题讨论】:

  • 如果它不是微不足道的解决方案,那么请展示您正在寻找的内容..

标签: python-3.x pandas timestamp


【解决方案1】:
t = pd.Timestamp.now()
(t - t.normalize()).total_seconds()

编辑

获取一小时的总秒数:

t = pd.Timestamp.now()
(t - t.to_period("H").start_time).total_seconds()

【讨论】:

  • 谢谢@HYRY。差不多了,但t.normalize() 给了我当天午夜的时间戳。
  • 我想我可以添加小时数,直到now()
  • 这可以做到:(now - now.normalize() - pd.Timedelta(hours=now.hour)).total_seconds()
  • @AmelioVazquez-Reina:获取分钟数:(t - t.to_period('H').start_time) / timedelta(minutes=1)
【解决方案2】:
In [2]: t = Timestamp('2015-09-02 19:33:55.714410')

In [3]: t
Out[3]: Timestamp('2015-09-02 19:33:55.714410')

In [4]: t.hour
Out[4]: 19

In [6]: t.second 
Out[6]: 55

In [7]: t.microsecond
Out[7]: 714410

In [8]: t.
t.asm8              t.dayofweek         t.freqstr           t.is_quarter_end    t.isoweekday        t.nanosecond        t.resolution        t.timetz            t.today             t.tzname            t.week
t.astimezone        t.dayofyear         t.fromordinal       t.is_quarter_start  t.max               t.normalize         t.second            t.to_datetime       t.toordinal         t.utcfromtimestamp  t.weekday
t.combine           t.days_in_month     t.fromtimestamp     t.is_year_end       t.microsecond       t.now               t.strftime          t.to_datetime64     t.tz                t.utcnow            t.weekofyear
t.ctime             t.daysinmonth       t.hour              t.is_year_start     t.min               t.offset            t.strptime          t.to_julian_date    t.tz_convert        t.utcoffset         t.year
t.date              t.dst               t.is_month_end      t.isocalendar       t.minute            t.quarter           t.time              t.to_period         t.tz_localize       t.utctimetuple      
t.day               t.freq              t.is_month_start    t.isoformat         t.month             t.replace           t.timetuple         t.to_pydatetime     t.tzinfo            t.value             

【讨论】:

  • 谢谢@Jeff。对不起,我知道。我应该澄清这个帖子。我的意思是获得 total 秒数(小数部分)。我认为的一个选项是使用DateOfffset 倒回到小时的开头,然后使用timedelta 查看总秒数,但我找不到将我的时间戳倒回到开头的DateOffset小时
【解决方案3】:
import datetime as dt   

In [63]:
last_hour = dt.datetime(t.year , t.month , t.day , t.hour , 0 , 0)

In [67]:
(t - last_hour).total_seconds()
Out[67]:
768.129

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-03
    • 2017-06-11
    • 1970-01-01
    • 2013-01-05
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 2018-05-23
    相关资源
    最近更新 更多