Create list of consecutive timestamps from the a first timestamp

Question:

I have a dataframe and I want to create a list of consecutive dates from the minimum timestamp.

The dataframe minimum timestamp is:

data_frame.date.min()

equals

datetime.date(2022, 2, 17)

How do I create a list of the next 5 dates in a list so it would look like:

my_list = ['2022-02-17', '2022-02-18','2022-02-19','2022-02-20','2022-02-21']

Thanks!

I need to create a list from a minimum date in datetime format in a pandas dataframe. I will be using this in a for loop, and i only want to keep the dates in the first 5 days of each variable.

Thanks!

Asked By: Kim Grauer

||

Answers:

You can use pandas.date_range:

>>> from datetime import datetime
>>> import pandas as pd
>>>
>>> start = datetime(2022, 1, 1)
>>> for d in pd.date_range(start=start, periods=5):
...     print(d.date())
...
2022-01-01
2022-01-02
2022-01-03
2022-01-04
2022-01-05

EDIT: If you want exactly the list in your question, you can use a list comprehension with it:

>>> [d.strftime("%Y-%m-%d") for d in pd.date_range(start=data_frame.date.min(), periods=5)]
['2022-02-17', '2022-02-18', '2022-02-19', '2022-02-20', '2022-02-21']
Answered By: jprebys

A possible solution would be to use datetime.timedelta with a listcomp :

from datetime import timedelta
​
N = 5
​
my_list = [(start_date + timedelta(days=d)).strftime("%Y-%m-%d") for d in range(N)]
​

NB: To assign it to an existing or new column of your (df), use df["new_col"] = my_list

Output :

print(my_list)
#['2022-02-17', '2022-02-18', '2022-02-19', '2022-02-20', '2022-02-21']
Answered By: Timeless
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.