Search code examples
pythonpandasdatetimestrptime

Adding a datetime column in pandas dataframe from minute values


I have a data frame where there is time columns having minutes from 0-1339 meaning 1440 minutes of a day. I want to add a column datetime representing the day 2021-3-21 including hh amd mm like this 1980-03-01 11:00 I tried following code

from datetime import datetime, timedelta
date = datetime.date(2021, 3, 21)
days = date - datetime.date(1900, 1, 1)
df['datetime'] = pd.to_datetime(df['time'],format='%H:%M:%S:%f') +  pd.to_timedelta(days, unit='d')

But the error seems like descriptor 'date' requires a 'datetime.datetime' object but received a 'int' Is there any other way to solve this problem or fixing this code? Please help to figure this out.

>>df
time
0
1
2
3
..
1339

I want to convert this minutes to particular format 1980-03-01 11:00 where I will use the date 2021-3-21 and convert the minutes tohhmm part. The dataframe will look like.

>df
datetime               time
2021-3-21 00:00         0
2021-3-21 00:01         1
2021-3-21 00:02         2
...

How can I format my data in this way?


Solution

  • Let's try with pd.to_timedelta instead to get the duration in minutes from time then add a TimeStamp:

    df['datetime'] = (
            pd.Timestamp('2021-3-21') + pd.to_timedelta(df['time'], unit='m')
    )
    

    df.head():

          time            datetime
    0        0 2021-03-21 00:00:00
    1        1 2021-03-21 00:01:00
    2        2 2021-03-21 00:02:00
    3        3 2021-03-21 00:03:00
    4        4 2021-03-21 00:04:00
    

    Complete Working Example with Sample Data:

    import numpy as np
    import pandas as pd
    
    df = pd.DataFrame({'time': np.arange(0, 1440)})
    
    df['datetime'] = (
            pd.Timestamp('2021-3-21') + pd.to_timedelta(df['time'], unit='m')
    )
    print(df)