ashish
ashish

Reputation: 87

How to make a Date Range in Python and convert into DataFrame

Suppose I have two Date inputs : 2020-01-20 11:35:00 and 2020-01-25 08:00:00 .

I want a output DataFrame as :

   time1                          time2  
-------------------------------------------
2020-01-20 11:35:00  |  2020-01-21 00:00:00  
2020-01-21 00:00:00  |  2020-01-22 00:00:00  
2020-01-22 00:00:00  |  2020-01-23 00:00:00  
2020-01-23 00:00:00  |  2020-01-24 00:00:00  
2020-01-24 00:00:00  |  2020-01-25 00:00:00  
2020-01-25 00:00:00  |  2020-01-25 08:00:00  

Upvotes: 1

Views: 534

Answers (2)

Umar.H
Umar.H

Reputation: 23099

no built in way to do this, we can use iloc and pd.date_range to assign the first and last dates and generate your date range.

t1 = pd.Timestamp('2020-01-20 11:35:00')
t2 = pd.Timestamp('2020-01-25 08:00:00')

df = pd.DataFrame({'Time1' : pd.date_range(t1.date(),t2.date())})
df = df.assign(Time2 = df['Time1'] + pd.DateOffset(days=1))

df.iloc[0,0] = t1
df.iloc[-1,1] = t2

print(df)

               Time1               Time2
0 2020-01-20 11:35:00 2020-01-21 00:00:00
1 2020-01-21 00:00:00 2020-01-22 00:00:00
2 2020-01-22 00:00:00 2020-01-23 00:00:00
3 2020-01-23 00:00:00 2020-01-24 00:00:00
4 2020-01-24 00:00:00 2020-01-25 00:00:00
5 2020-01-25 00:00:00 2020-01-25 08:00:00

Upvotes: 2

Ben.T
Ben.T

Reputation: 29635

You can use date_range with both dates and then create the dataframe.

d1 = pd.to_datetime('2020-01-20 11:35:00')
d2 = pd.to_datetime('2020-01-25 08:00:00')

l = pd.date_range(d1.date(), d2.date(), freq='d').tolist()[1:] #remove the first date
df = pd.DataFrame({'time1':[d1] + l, 'time2':l + [d2]})
print (df)
                time1               time2
0 2020-01-20 11:35:00 2020-01-21 00:00:00
1 2020-01-21 00:00:00 2020-01-22 00:00:00
2 2020-01-22 00:00:00 2020-01-23 00:00:00
3 2020-01-23 00:00:00 2020-01-24 00:00:00
4 2020-01-24 00:00:00 2020-01-25 00:00:00
5 2020-01-25 00:00:00 2020-01-25 08:00:00

Upvotes: 2

Related Questions