如何包含动态时间?

2024-01-10

我正在尝试提取有关时间段的日志。当没有时,下面的程序运行得很好。给出小时数,并提取该范围内的日志。

但现在我还包括动态给出的开始和结束。即说之间8 am to 8pm or 6am to 8am等等。

我怎样才能得到它?当前程序中的任何编辑也可以,或者单独的程序也可以。

输入:迷你版INPUT https://www.dropbox.com/s/varv1lyb5uskexh/dart_small.csv?dl=0

Code:

import pandas as pd
from datetime import datetime,time
import numpy as np

fn = r'00_Dart.csv'
cols = ['UserID','StartTime','StopTime', 'gps1', 'gps2']
df = pd.read_csv(fn, header=None, names=cols)

df['m'] = df.StopTime + df.StartTime
df['d'] = df.StopTime - df.StartTime

# 'start' and 'end' for the reporting DF: `r`
# which will contain equal intervals (1 hour in this case)
start = pd.to_datetime(df.StartTime.min(), unit='s').date()
end = pd.to_datetime(df.StopTime.max(), unit='s').date() + pd.Timedelta(days=1)

# building reporting DF: `r`
freq = '1H'  # 1 Hour frequency
idx = pd.date_range(start, end, freq=freq)
r = pd.DataFrame(index=idx)
r['start'] = (r.index - pd.datetime(1970,1,1)).total_seconds().astype(np.int64)

# 1 hour in seconds, minus one second (so that we will not count it twice)
interval = 60*60 - 1

r['LogCount'] = 0
r['UniqueIDCount'] = 0

for i, row in r.iterrows():
        # intervals overlap test
        # https://en.wikipedia.org/wiki/Interval_tree#Overlap_test
        # i've slightly simplified the calculations of m and d
        # by getting rid of division by 2,
        # because it can be done eliminating common terms
    u = df[np.abs(df.m - 2*row.start - interval) < df.d + interval].UserID
    r.ix[i, ['LogCount', 'UniqueIDCount']] = [len(u), u.nunique()]

r['Date'] = pd.to_datetime(r.start, unit='s').dt.date
r['Day'] = pd.to_datetime(r.start, unit='s').dt.weekday_name.str[:3]
r['StartTime'] = pd.to_datetime(r.start, unit='s').dt.time
r['EndTime'] = pd.to_datetime(r.start + interval + 1, unit='s').dt.time

#r.to_csv('results.csv', index=False)
#print(r[r.LogCount > 0])
#print (r['StartTime'], r['EndTime'], r['Day'], r['LogCount'], r['UniqueIDCount'])

rout =  r[['Date', 'StartTime', 'EndTime', 'Day', 'LogCount', 'UniqueIDCount'] ]
#print rout
rout.to_csv('one_hour.csv', index=False, header=False)

Edit:

简而言之,我应该能够给予StartTime and EndTIme在节目中。下面的代码非常接近我想要做的事情。但如何将其转换为熊猫。

from datetime import datetime,time

start = time(8,0,0)
end =   time(20,0,0)

with open('USC28days_0_20', 'r') as infile, open('USC28days_0_20_time','w') as outfile:
    for row in infile:
        col = row.split()
        t1 = datetime.fromtimestamp(float(col[2])).time()
        t2 = datetime.fromtimestamp(float(col[3])).time()
        print (t1 >= start and t2 <= end)

编辑二:Pandas 中的工作答案

从所选答案中选取@MaxU 的答案。下面的代码在给定的之间删除所需的日志组StartTime and StopTime

import pandas as pd
from datetime import datetime,time
import numpy as np

fn = r'00_Dart.csv'
cols = ['UserID','StartTime','StopTime', 'gps1', 'gps2']

df = pd.read_csv(fn, header=None, names=cols)

#df['m'] = df.StopTime + df.StartTime
#df['d'] = df.StopTime - df.StartTime

# filter input data set ... 
start_hour = 8
end_hour = 9
df = df[(pd.to_datetime(df.StartTime, unit='s').dt.hour >= start_hour) & (pd.to_datetime(df.StopTime, unit='s').dt.hour <= end_hour)]

print df

df.to_csv('time_hour.csv', index=False, header=False)

But:如果有可能控制分钟和秒也将是一个很好的解决方案。

目前,这还剥离了具有小时的日志StopTime还包括下一个小时之前的分钟和秒数。

就像是

start_hour = 8:0:0
end_hour = 9:0:0 - 1 # -1 to get the logs until 8:59:59

但这给了我一个错误


尝试这个:

import pandas as pd
from datetime import datetime,time
import numpy as np

fn = r'D:\data\gDrive\data\.stack.overflow\2016-07\dart_small.csv'
cols = ['UserID','StartTime','StopTime', 'gps1', 'gps2']

df = pd.read_csv(fn, header=None, names=cols)

df['m'] = df.StopTime + df.StartTime
df['d'] = df.StopTime - df.StartTime

# filter input data set ... 
start_hour = 8
end_hour = 20
df = df[(pd.to_datetime(df.StartTime, unit='s').dt.hour >= 8) & (pd.to_datetime(df.StartTime, unit='s').dt.hour <= 20)]


# 'start' and 'end' for the reporting DF: `r`
# which will contain equal intervals (1 hour in this case)
start = pd.to_datetime(df.StartTime.min(), unit='s').date()
end = pd.to_datetime(df.StopTime.max(), unit='s').date() + pd.Timedelta(days=1)

# building reporting DF: `r`
freq = '1H'  # 1 Hour frequency
idx = pd.date_range(start, end, freq=freq)
r = pd.DataFrame(index=idx)
r = r[(r.index.hour >= start_hour) & (r.index.hour <= end_hour)]
r['start'] = (r.index - pd.datetime(1970,1,1)).total_seconds().astype(np.int64)

# 1 hour in seconds, minus one second (so that we will not count it twice)
interval = 60*60 - 1

r['LogCount'] = 0
r['UniqueIDCount'] = 0

for i, row in r.iterrows():
        # intervals overlap test
        # https://en.wikipedia.org/wiki/Interval_tree#Overlap_test
        # i've slightly simplified the calculations of m and d
        # by getting rid of division by 2,
        # because it can be done eliminating common terms
    u = df[np.abs(df.m - 2*row.start - interval) < df.d + interval].UserID
    r.ix[i, ['LogCount', 'UniqueIDCount']] = [len(u), u.nunique()]

r['Date'] = pd.to_datetime(r.start, unit='s').dt.date
r['Day'] = pd.to_datetime(r.start, unit='s').dt.weekday_name.str[:3]
r['StartTime'] = pd.to_datetime(r.start, unit='s').dt.time
r['EndTime'] = pd.to_datetime(r.start + interval + 1, unit='s').dt.time

#r.to_csv('results.csv', index=False)
#print(r[r.LogCount > 0])
#print (r['StartTime'], r['EndTime'], r['Day'], r['LogCount'], r['UniqueIDCount'])

rout =  r[['Date', 'StartTime', 'EndTime', 'Day', 'LogCount', 'UniqueIDCount'] ]
#print rout

旧答案:

from_time = '08:00'
to_time = '18:00'
rout.between_time(from_time, to_time).to_csv('one_hour.csv', index=False, header=False)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何包含动态时间? 的相关文章

随机推荐

  • Android Wear 启动器

    我想知道 Android Wear 启动器 如 Swipify 和 Wear Mini Launcher 如何拦截Android Wear主屏幕上的触摸事件 到目前为止 我已尝试将 onTouch 和 onClick 侦听器添加到应用程序中
  • Python 的 argparse 可以像 gnu getopt 一样排列参数顺序吗?

    GNU getopt 和使用它的命令行工具允许选项和参数交错 称为排列选项 请参阅http www gnu org software libc manual html node Using Getopt html Using Getopt
  • 如何在序列最后一次出现时分割字符串

    目标 具有内置分隔符的字符串应拆分为一个 int 和另一个字符串 如果分隔符序列 出现多次 则字符串应始终拼接在最后一个 是否有类似 C 中的 string lastIndexOf 之类的运算符 这就是我的解析器的样子 func parse
  • 如何让 Clang 忽略特定块中的特定警告?

    我正在检查带有类型特征的数值范围 无符号类型会生成警告 Comparison of unsigned expression gt 0 is always true 如何禁用特定代码范围内的某些警告 我用的是海湾合作委员会风格 pragma与
  • 如何将AppBarLayout的高度设置为0

    我的布局文件如下
  • 如何使用 C++ 在 WinUI 3 中获取页面上的主窗口句柄

    我正在使用 C 开发 WinUI 3 演示 我想要一个主窗口处理程序或本机窗口处理程序来打开一个Picker在一个Page 我正在使用的代码块工作正常Window但它不起作用Page auto windowNative this gt tr
  • 上传ipa到googledrive

    我的要求是 如果我在谷歌驱动器或共享点中上传 ipa 文件 那么测试人员应该能够从驱动器将 ipa 安装到他的设备中 而无需使用 iTunes 是否可以 我可以通过在服务器中部署 ipa plist 和 index html 文件来实现这一
  • Git 在日志中显示所有分支(但不显示存储)

    我有一个 Git 别名 它扩展为 git log graph oneline all decorate 根据man git log有几个可疑的选项 not and branches 但我无法让它正常工作 我应该如何编辑它来隐藏隐藏的东西 F
  • 打印未从页面顶部边缘开始

    我正在尝试打印一些strings using Graphicss DrawString 我已将边距设置为printdocument但不从页面的原点开始 我已经设定margins to 0 0 0 0 但不知怎的 它打印在页面顶部边缘下方半厘
  • 现在无法查询选项卡(用户可能正在拖动选项卡)

    我有一个 chrome 扩展 可以通过以下代码访问活动选项卡 chrome tabs query active true result gt 这一直工作得非常好 直到最近的更新 我不再能够查询该选项卡 并在控制台中打印以下错误 Tabs c
  • Cocoa OSX:如何使图像可拖动

    我有一个带有图像的面板 我想让它可以通过 拖动 将文件 不是图像 图像仅作为文件的图标 复制到文件夹中应用程序外部的图像以及接受拖入其中的文件的任何其他应用程序 例如 Finder 我怎样才能做到这一点 我实施了NSDraggingSour
  • iOS7 中固定页眉和页脚的网页滚动问题

    这对我来说很难解释 但我会尝试 首先 我的网页在 iOS6 x Android W7 中的 mobilebrowser 以及桌面浏览器 IE9 Safari 和 Chrome 上运行 该问题发生在iOS7中的苹果移动Safari浏览器中 我
  • 如何在cordova android应用程序中使用proguard

    我有一个完成的 cordova 项目 我想使用 proguard 来防止其他人对 APK 进行逆向工程 但我在这方面遇到了困难 In http developer android com tools help proguard html h
  • 无法执行简单的导航到查看和返回 SwiftUI 导航栏按钮

    我正在尝试使用 SwiftUI 进行从一个视图到另一个视图的简单导航 一个栏按钮项目 我尝试了三种不同的方法来调用新视图 在正文视图中使用 Button 可以 但在导航中使用 NavigationBarItems bar 以两种不同的方式失
  • 如何在android中创建自定义通知

    我需要创建一个自定义通知而不是 android 中的默认通知 当前通知有一个图标 标题和消息 如下图所示 我想要它像这样定制 我怎样才能做到这一点 通知视图 普通视图 普通视图中的通知出现在高度高达 64 dp 的区域中 即使您创建具有大视
  • 如何将两个函数传递给react中的onClick事件

    我想将两个函数传递给onClick事件是handleSubmit and handleDelete to the HomePage js来自HomeItem js 这是我的错误 No duplicate props allowed reac
  • C# - 通过相同的方法传递不同类型的对象

    原始问题 所以我有这 3 个对象 public class obj1 public int Id get set public string Name get set public class obj2 public int AccNum
  • Android 版 Google 登录:无法解析 RC_SIGN_IN

    我正在尝试通过移动应用程序通过后端服务器进行身份验证 我正在关注这个文档 https developers google com identity sign in android sign in https developers googl
  • 使用 Google Apps 脚本标记 Gmail 邮件(不是整个线程)

    是否可以搜索带有 应用程序脚本队列 标签的消息并为这些特定消息 而不是整个线程 提供新标签 当我使用 GmailApp search label Apps script queue 时 我收到请求的邮件 但是当我为这些邮件分配新标签时 该线
  • 如何包含动态时间?

    我正在尝试提取有关时间段的日志 当没有时 下面的程序运行得很好 给出小时数 并提取该范围内的日志 但现在我还包括动态给出的开始和结束 即说之间8 am to 8pm or 6am to 8am等等 我怎样才能得到它 当前程序中的任何编辑也可