4

I have some measurements that happened on specific days in a dictionary. It looks like

date_dictionary['YYYY-MM-DD'] = measurement.

I want to calculate the variance between the measurements within 7 days from a given date. When I convert the date strings to a datetime.datetime, the result looks like a tuple or an array, but doesn't behave like one.

Is there an easy way to generate all the dates one week from a given date? If so, how can I do that efficiently?

user3600497
  • 1,621
  • 1
  • 18
  • 22
  • Show us more code... how do you convert? how does it behave? how do you expect it to behave? what do you mean by "variance"? – shx2 Jul 22 '15 at 05:00
  • Variance is a statistic. I convert the strings by executing `t = date_string.split('-')` and `datetime.datetime( year = int(t[0]), month = int(t[1]), day = int(t[2]) )`. I want datetime to behave like an array or list, so I could say `t=datetime.datetime(2015,02,11)` and `t+(0,0,7) = datetime.datetime(2015,02,18)` – Demetri Pananos Jul 22 '15 at 05:04

2 Answers2

4

You can do this using - timedelta . Example -

>>> from datetime import datetime,timedelta
>>> d = datetime.strptime('2015-07-22','%Y-%m-%d')
>>> for i in range(1,8):
...     print(d + timedelta(days=i))
...
2015-07-23 00:00:00
2015-07-24 00:00:00
2015-07-25 00:00:00
2015-07-26 00:00:00
2015-07-27 00:00:00
2015-07-28 00:00:00
2015-07-29 00:00:00

You do not actually need to print it, datetime object + timedelta object returns a datetime object. You can use that returned datetime object directly in your calculation.

Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
4

Using datetime, to generate all 7 dates following a given date, including the the given date, you can do:

import datetime
dt = datetime.datetime(...)
week_dates = [ dt + datetime.timedelta(days=i) for i in range(7) ]

There are libraries providing nicer APIs for performing datetime/date operations, most notably pandas (though it includes much much more). See pandas.date_range.

shx2
  • 61,779
  • 13
  • 130
  • 153