edgarmtze
edgarmtze

Reputation: 25038

How to add a date column in pandas that increases one hour each row given a start date Timestamp?

start_date = '2020-05-15 01:00:00'

data_test = {'a':  [1, 2,13,14,15],
             'b':  [11,12,13,14,15]
             }
df_test = pd.DataFrame (data_test, columns = ['a','b'])
df_test['date'] = pd.Timestamp(start_date)
df_test

    a   b   date
0   1   11  2020-05-15 01:00:00
1   2   12  2020-05-15 01:00:00
2   13  13  2020-05-15 01:00:00
3   14  14  2020-05-15 01:00:00
4   15  15  2020-05-15 01:00:00

What needs to be done to get:

    a   b   date
0   1   11  2020-05-15 01:00:00
1   2   12  2020-05-15 02:00:00
2   13  13  2020-05-15 03:00:00
3   14  14  2020-05-15 04:00:00
4   15  15  2020-05-15 05:00:00

Upvotes: 2

Views: 61

Answers (2)

sammywemmy
sammywemmy

Reputation: 28659

An alternative to @Ben.T's solution, using the timedelta :

# conveniently used the index since you are
# interested in a one hour progression
df_test['date'] = df_test['date'] + pd.to_timedelta(df_test.index, 'hour')

print(df_test)

    a   b   date
0   1   11  2020-05-15 01:00:00
1   2   12  2020-05-15 02:00:00
2   13  13  2020-05-15 03:00:00
3   14  14  2020-05-15 04:00:00
4   15  15  2020-05-15 05:00:00

Upvotes: 1

Ben.T
Ben.T

Reputation: 29635

you can use pd.date_range like:

df_test['date'] = pd.date_range(start=start_date, freq='1H', periods=len(df_test))
print(df_test)
    a   b                date
0   1  11 2020-05-15 01:00:00
1   2  12 2020-05-15 02:00:00
2  13  13 2020-05-15 03:00:00
3  14  14 2020-05-15 04:00:00
4  15  15 2020-05-15 05:00:00

Upvotes: 2

Related Questions