Home > Net >  Want to convert given format into actual DateTime format
Want to convert given format into actual DateTime format

Time:12-07

I want to convert this time format to the actual DateTime format in Python. Hr:Min:Sec in this format. Can Anyone suggest to me how to do it, using pandas? enter image description here

CodePudding user response:

The pandas function pd.to_timedelta() seems to work pretty well on these. That will set it to a timedelta, not a datetime, but it looks like you aren't actually setting things to a date or a time, but rather a duration of time; i.e. a timedelta.

You'll first need to remove the brackets from each element, and then run each column through pd.to_timedelta(). Something like this should work, which makes a new df2. You could just save it over df[col] if you wanted.

for col in df.columns:
    df2[col] = df[col].str.strip('\[\]') #removes the [ and ] characters
    df2[col] = pd.to_timedelta(df2[col])

That will give you stuff in this general timedelta style:

                0               1
0 0 days 00:10:00 0 days 00:20:00
1 0 days 01:00:00 0 days 03:00:00

From there, you can tinker with the format as needed for what specifically you want.

CodePudding user response:

It is easier to remove the square braces as they are reserved for optional parts (I personally haven't found a way to escape them):

pd.to_timedelta(df['x'].str.strip('[ ]'))
  • Related