Convert a digit code into datetime format in a Pandas Dataframe

Question:

I have a pandas dataframe that has a column with a 5 digit code that represent a day and time, and it works like following:

1 – The first three digits represent the day;

2 – The last two digits represent the hour:minute:second.

Example1: The first row have the code 19501, so the 195 represent the 1st of January of 2009 and the 01 part represents the time from 00:00:00 to 00:29:59;

Example2: In the second row i have the code 19502 which is the 1st of January of 2009 from 00:30:00 to 00:59:59;

Example3: Another example, 19711 would be the 3rd of January of 2009 from 05:00:00 to 05:29:59;

Example4: The last row is the code 73048, which represent the 20th of June of 2010 from 23:30:00 to 23:59:59.

Any ideas in how can I convert this 5 digit code into a proper datetime format?

Asked By: Murilo

||

Answers:

I’m assuming your column is numeric.

import datetime as dt

df = pd.DataFrame({'code': [19501, 19502, 19711, 73048]})
df['days'] = pd.to_timedelta(df['code']//100, 'D')
df['half-hours'] = df['code']%100
df['hours'] = pd.to_timedelta(df['half-hours']//2, 'h')
df['minutes'] = pd.to_timedelta(df['half-hours']%2*30, 'm')

base_day = dt.datetime(2009, 1, 1) - dt.timedelta(days = 195)

df['dt0'] = base_day + df.days + df.hours + df.minutes - dt.timedelta(minutes = 30)
df['dt1'] = base_day + df.days + df.hours + df.minutes - dt.timedelta(seconds = 1)
Answered By: Michael Cao

A simple solution, add the days to 2008-06-20, add the (time-1)*30min;

df = pd.DataFrame({'code': [19501, 19502, 19711, 73048]})

d, t = df['code'].divmod(100)

df['datetime'] = (
   pd.to_timedelta(d, unit='D')
     .add(pd.Timestamp('2008-06-20'))
     .add(pd.to_timedelta((t-1)*30, unit='T'))
)

NB. this gives you the start of the period, for the end replace (t-1)*30 by t*30-1.

Output:


    code            datetime
0  19501 2009-01-01 00:00:00
1  19502 2009-01-01 00:30:00
2  19711 2009-01-03 05:00:00
3  73048 2010-06-20 23:30:00
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.