0

I have a full year of data every minute:

dayofyear   hourofday   minuteofhour    
1            0           0  
.
.
365          23         57  
365          23         58 
365          23         59  

I converted the dayofyear to a date:

df['date']=pd.to_datetime(df['dayofyear'], unit='D', origin=pd.Timestamp('2009-12-31'))

    dayofyear   hourofday   minuteofhour    date
1   0   0 2010-01-01
1   0   1 2010-01-01
1   0   2 2010-01-01
1   0   3 2010-01-01
1   0   4 2010-01-01

How can I combine the hourofday and minuteofhour with date in order to create a proper timestamp?

Like this maybe: '2010-12-30 19:00:00'

So that I can perform other time-filtering/subsetting etc in pandas later.

maximusdooku
  • 5,242
  • 10
  • 54
  • 94

2 Answers2

1

Convert the hourofday and minuteofhour columns into a TimeDelta, then add it to the date column:

df['timestamp'] = df['date'] + pd.to_timedelta(df['hourofday'].astype('str') + ':' + df['minuteofhour'].astype('str') + ':00')
Code Different
  • 90,614
  • 16
  • 144
  • 163
0
import pandas as pd
from datetime import datetime, timedelta


df = pd.DataFrame({
    'dayofyear': (365, ),
    'hourofday': (23, ),
    'minuteofhour': (57, ),
})


def parse_dt(x):
    dt = datetime(2010, 1, 1) + timedelta(int(x['dayofyear']) - 1)
    dt = dt.replace(hour=x['hourofday'], minute=x['minuteofhour'])
    x['dt'] = dt
    return x


df = df.apply(parse_dt, axis=1)
print(df)

#   dayofyear  hourofday  minuteofhour                  dt
#0        365         23            57 2010-12-31 23:57:00

Hope this helps

Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75