Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 792
user3600497 Avatar asked Mar 15 '23 08:03

user3600497


2 Answers

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.

like image 64
Anand S Kumar Avatar answered Apr 08 '23 08:04

Anand S Kumar


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.

like image 30
shx2 Avatar answered Apr 08 '23 06:04

shx2