Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Create a dataframe from a date range in python

Given an interval from two dates, which will be a Python TimeStamp.

create_interval('2022-01-12', '2022-01-17', 'Holidays')

Create the following dataframe:

date interval_name
2022-01-12 00:00:00 Holidays
2022-01-13 00:00:00 Holidays
2022-01-14 00:00:00 Holidays
2022-01-15 00:00:00 Holidays
2022-01-16 00:00:00 Holidays
2022-01-17 00:00:00 Holidays

If it can be in a few lines of code I would appreciate it. Thank you very much for your help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I hope I coded exactly what you need.

import pandas as pd

def create_interval(ts1, ts2, interval_name):
    ts_list_dt = pd.date_range(start=ts1, end=ts2).to_pydatetime().tolist()
    ts_list = list(map(lambda x: ''.join(str(x)), ts_list_dt))
    d = {'date': ts_list, 'interval_name': [interval_name]*len(ts_list)}
    df = pd.DataFrame(data=d)
    return df

df = create_interval('2022-01-12', '2022-01-17', 'Holidays')
print(df)

output:

         date             interval_name
0  2022-01-12 00:00:00      Holidays
1  2022-01-13 00:00:00      Holidays
2  2022-01-14 00:00:00      Holidays
3  2022-01-15 00:00:00      Holidays
4  2022-01-16 00:00:00      Holidays
5  2022-01-17 00:00:00      Holidays
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading