vicemagui
vicemagui

Reputation: 151

Pandas Series of hour values to Series of dates

I have a time series covering January of 1979 with 6 hours time deltas. Time format is in continuous hour range:

1
7
13
18
25
31
.
.
.
739

Is it possible to convert these ints to dates? For instance:

1979/01/01 - 1:00
1979/01/01 - 7:00  
1979/01/01 - 13:00
1979/01/01 - 18:00
1979/01/02 - 1:00

Thank you so much!

Upvotes: 1

Views: 200

Answers (3)

spinkus
spinkus

Reputation: 8550

Could also just do this:

from datetime import datetime, timedelta

s = pd.Series([1,7,13,18,25])
s = s.apply(lambda h: datetime(1979, 1, 1) + timedelta(hours=h))
print(s)

Returns:

0   1979-01-01 01:00:00
1   1979-01-01 07:00:00
2   1979-01-01 13:00:00
3   1979-01-01 18:00:00
4   1979-01-02 01:00:00
dtype: datetime64[ns]

Upvotes: 1

Anton vBR
Anton vBR

Reputation: 18906

Here is another way:

import pandas as pd

s = pd.Series([1,7,13])    
s = pd.to_datetime(s*1e9*60*60+ pd.Timestamp(1979,1,1).value)
print(s)

Returns:

0   1979-01-01 01:00:00
1   1979-01-01 07:00:00
2   1979-01-01 13:00:00
dtype: datetime64[ns]

Upvotes: 3

user3483203
user3483203

Reputation: 51165

Setup

df = pd.DataFrame({'hour': [1,7,13,18,25,31]})

Use pd.to_datetime with the unit flag, and set the origin flag to the beginning of your desired year.

pd.to_datetime(df.hour, unit='h', origin='1979-01-01')

0   1979-01-01 01:00:00
1   1979-01-01 07:00:00
2   1979-01-01 13:00:00
3   1979-01-01 18:00:00
4   1979-01-02 01:00:00
5   1979-01-02 07:00:00
Name: hour, dtype: datetime64[ns]

Upvotes: 4

Related Questions