我列出了日期系列:
import pandas as pd
daterange2016 = pd.date_range("2016-04-25 00:00:00", "2016-04-29 21:00:00", freq="30min")
但是,我想要一个函数来获取日期时间并知道时间属于哪个时间间隔。我不想改变间隔。我怎么能这样做?
类似的东西(这里是伪代码):
def datetimesorter(givendate):
if givendate:
df['pd_time_interval_that_givendate_belongs_to'] = givendate
提前感谢您的帮助
更新:我想出了这个,它有效,但我不会删除这个问题,以防它有助于某人
def daterangefinder(datetime):
for intervals in daterange2016:
if intervals <= datetime < intervals+1:
return intervals
else:
pass
答案 0 :(得分:1)
您可以尝试IIUC:
<div id="dateInput" ng-change="doSomething($event)"></div>
import pandas as pd
daterange2016 = pd.date_range("2016-04-25 00:00:00", "2016-04-25 05:00:00", freq="30min")
print daterange2016
DatetimeIndex(['2016-04-25 00:00:00', '2016-04-25 00:30:00',
'2016-04-25 01:00:00', '2016-04-25 01:30:00',
'2016-04-25 02:00:00', '2016-04-25 02:30:00',
'2016-04-25 03:00:00', '2016-04-25 03:30:00',
'2016-04-25 04:00:00', '2016-04-25 04:30:00',
'2016-04-25 05:00:00'],
dtype='datetime64[ns]', freq='30T')
df = pd.DataFrame(daterange2016, columns=['d1'])
df['d2']= df.d1.shift(-1)
print df
d1 d2
0 2016-04-25 00:00:00 2016-04-25 00:30:00
1 2016-04-25 00:30:00 2016-04-25 01:00:00
2 2016-04-25 01:00:00 2016-04-25 01:30:00
3 2016-04-25 01:30:00 2016-04-25 02:00:00
4 2016-04-25 02:00:00 2016-04-25 02:30:00
5 2016-04-25 02:30:00 2016-04-25 03:00:00
6 2016-04-25 03:00:00 2016-04-25 03:30:00
7 2016-04-25 03:30:00 2016-04-25 04:00:00
8 2016-04-25 04:00:00 2016-04-25 04:30:00
9 2016-04-25 04:30:00 2016-04-25 05:00:00
10 2016-04-25 05:00:00 NaT
如果您需要将date = pd.to_datetime('2016-04-25 02:15:08')
print date
2016-04-25 02:15:08
print (df.d1 < date) & (df.d2 > date)
0 False
1 False
2 False
3 False
4 True
5 False
6 False
7 False
8 False
9 False
10 False
dtype: bool
print df[(df.d1 < date) & (df.d2 > date)].d1
4 2016-04-25 02:00:00
Name: d1, dtype: datetime64[ns]
添加到新列date
,请使用loc
:
d3