The Python Book

datetime deltatime
20160930

# Days between dates

Q: how many days are there in between these days ?

``'29 sep 2016', '7 jul 2016', '28 apr 2016', '10 mar 2016', '14 jan 2016'``

Solution:

``````from datetime import datetime,timedelta

a=map(lambda x: datetime.strptime(x,'%d %b %Y'),
['29 sep 2016', '7 jul 2016', '28 apr 2016', '10 mar 2016', '14 jan 2016'] )

def dr(ar):
if len(ar)>1:
print "{:%d %b %Y} .. {} .. {:%d %b %Y} ".format(
ar[0], (ar[0]-ar[1]).days, ar[1])
dr(ar[1:]) ``````

Output:

``````dr(a)

29 Sep 2016 .. 84 .. 07 Jul 2016
07 Jul 2016 .. 70 .. 28 Apr 2016
28 Apr 2016 .. 49 .. 10 Mar 2016
10 Mar 2016 .. 56 .. 14 Jan 2016 ``````
datetime pandas numpy
20141025

# Dataframe with date-time index

Create a dataframe df with a datetime index and some random values: (note: see 'simpler' dataframe creation further down)

Output:

``````    In [4]: df.head(10)
Out[4]:
value
2009-12-01     71
2009-12-02     92
2009-12-03     64
2009-12-04     55
2009-12-05     99
2009-12-06     51
2009-12-07     68
2009-12-08     64
2009-12-09     90
2009-12-10     57
[10 rows x 1 columns]``````

Now select a week of data

Output: watchout selects 8 days!!

``````    In [235]: df[d1:d2]
Out[235]:
value
2009-12-10     99
2009-12-11     70
2009-12-12     83
2009-12-13     90
2009-12-14     60
2009-12-15     64
2009-12-16     59
2009-12-17     97
[8 rows x 1 columns]

In [236]: df[d1:d1+dt.timedelta(days=7)]
Out[236]:
value
2009-12-10     99
2009-12-11     70
2009-12-12     83
2009-12-13     90
2009-12-14     60
2009-12-15     64
2009-12-16     59
2009-12-17     97
[8 rows x 1 columns]

In [237]: df[d1:d1+dt.timedelta(weeks=1)]
Out[237]:
value
2009-12-10     99
2009-12-11     70
2009-12-12     83
2009-12-13     90
2009-12-14     60
2009-12-15     64
2009-12-16     59
2009-12-17     97
[8 rows x 1 columns]``````

## Postscriptum: a simpler way of creating the dataframe

An index of a range of dates can also be created like this with pandas:

``pd.date_range('20091201', periods=31)``

Hence the dataframe:

``df=pd.DataFrame(np.random.randint(50,100,31), index=pd.date_range('20091201', periods=31))``

Notes by Willem Moors. Generated on momo:/home/willem/sync/20151223_datamungingninja/pythonbook at 2019-07-31 19:22