Home > OS >  How to convert object to time
How to convert object to time

Time:06-21

How can I convert "2022-03-01 1:01:42 AM" to just 1:01:42?

I tried to strip just the time out and convert to datetime format, but it keeps adding the current date to the beginning. Otherwise, it doesn't properly convert to datetime format so I can plot it later. All I want is the time in datetime format.

def time():
    df['Time'] = df['TIME'].apply(lambda x: x.split(' ')[1])
    df['Time'] = pd.to_datetime(df.Time, format = '%H:%M:%S', errors='ignore').dt.time

CodePudding user response:

How about using simple date format

from datetime import datetime

now = datetime.now()
print (now.strftime("%H:%M:%S"))

CodePudding user response:

No need to split it. just simply:

import pandas as pd

df = pd.DataFrame({'ID':[1,2],
                   'TIME':['2022-03-01 1:01:42 AM', '2022-03-01 12:01:42 PM']})

df['Time'] = pd.to_datetime(df.TIME, errors='ignore').dt.time

Output:

df.iloc[0]['Time']
Out[1]: datetime.time(1, 1, 42)
  • Related