user3600497
user3600497

Reputation: 1661

How can I get all the dates within a week of a certain day using datetime?

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?

Upvotes: 4

Views: 2211

Answers (2)

shx2
shx2

Reputation: 64318

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.

Upvotes: 4

Anand S Kumar
Anand S Kumar

Reputation: 90899

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.

Upvotes: 4

Related Questions