Home > Software design >  Add a column which shows the timestamp with an increasing step
Add a column which shows the timestamp with an increasing step

Time:04-30

I have a dataframe with on column, I want to add another columns which shows the timestamp. I want the increasing time as 5 min. Here is an example:

import pandas as pd
df = pd.DataFrame()
df['value'] = [57,43, 55, 64]

The data frame which i want is like this:

enter image description here

Could you please help how to build a df like that? Thanks

CodePudding user response:

You can use date_range.

As index:

df = df.set_index(pd.date_range('2015-02-26 21:42:53', freq='5min', periods=len(df)))

output:

                     value
2015-02-26 21:42:53     57
2015-02-26 21:47:53     43
2015-02-26 21:52:53     55
2015-02-26 21:57:53     64

With index name:

df = df.set_index(pd.date_range('2015-02-26 21:42:53',
                                freq='5min',
                                periods=len(df)).rename('timestamp'))

output:

                     value
timestamp                 
2015-02-26 21:42:53     57
2015-02-26 21:47:53     43
2015-02-26 21:52:53     55
2015-02-26 21:57:53     64

As new column:

df['date'] = pd.date_range('2015-02-26 21:42:53', freq='5min', periods=len(df))

output:

   value                date
0     57 2015-02-26 21:42:53
1     43 2015-02-26 21:47:53
2     55 2015-02-26 21:52:53
3     64 2015-02-26 21:57:53

CodePudding user response:

import datetime
base = datetime.datetime.today()
date_list = [str(base - datetime.timedelta(minutes=x)) for x in range(5, 100, 5)]

df['date'] = date_list
  • Related