【问题标题】:Get the Difference between Datetime in terms of hours with two round off set to 2以小时为单位获取日期时间之间的差异,并将两个舍入设置为 2
【发布时间】:2020-11-24 08:55:23
【问题描述】:

通过四舍五入到小数点后两位来获取两个日期时间之间的差异

> `Started                     Ended`                     Hours
   2020-10-01 09:29:20         2020-10-01 17:43:28         8.2
   2020-10-31 09:26:43         2020-10-31 18:57:40         9.5
   2020-10-31 09:18:57         2020-10-31 21:06:30         11.8

【问题讨论】:

    标签: python pandas numpy dataframe datetime


    【解决方案1】:

    将to_datetime 与Series.sub 和Series.dt.total_seconds 一起使用,最后除以Series.div 并使用Series.round:

    df['Started'] = pd.to_datetime(df['Started'])
    df['Ended'] = pd.to_datetime(df['Ended'])
    
    df['new'] = df['Ended'].sub(df['Started']).dt.total_seconds().div(3600).round(2)
    print (df)
                  Started               Ended  Hours    new
    0 2020-10-01 09:29:20 2020-10-01 17:43:28    8.2   8.24
    1 2020-10-31 09:26:43 2020-10-31 18:57:40    9.5   9.52
    2 2020-10-31 09:18:57 2020-10-31 21:06:30   11.8  11.79
    

    【讨论】:

      【解决方案2】:

      另一个例子:

      from datetime import datetime
      beg = '08:00:10'
      end = '17:16:24' 
      
      print('end = ',end, 'type: ',type(end))
      
      dur = datetime.strptime(end, '%H:%M:%S') - datetime.strptime(beg, '%H:%M:%S')
      
      result = dur.total_seconds()/3600
      
      result = round(result, 2)
      
      print(result)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-11
        • 2012-12-03
        • 1970-01-01
        • 2013-05-14
        • 2017-06-24
        • 1970-01-01
        • 1970-01-01
        • 2013-09-15
        相关资源
        最近更新 更多