Home > Mobile >  Convert date time to day and time
Convert date time to day and time

Time:01-30

I have a variable in a df that looks like this

Datetime
10/27/2020 2:28:28 PM
8/2/2020   3:30:18 AM
6/15/2020  5:38:19 PM

How can I change it to this using python?

Date            Time
10/27/2020      14:28:28
8/2/2020        3:30:18
6/15/2020       17:38:19

I understand how to separate date and time, but unsure of how to convert it to 24 hour time.

CodePudding user response:

I think this is source you want:

from dateutil.parser import parse
dt = parse("10/27/2020 2:28:28")
print(dt)
# 2020-10-27 02:28:28
# Create Date
date=f"{str(dt.year)}/{str(dt.month)}/{str(dt.day)}"
# Create Time
time=f"{str(dt.hour)}:{str(dt.minute)}:{str(dt.second)}"

CodePudding user response:

You can use pd.to_datetime to convert a scalar, array-like, Series or DataFrame/dict-like to a pandas datetime object. Then, you can use the accessor object for datetimelike properties of the Series values (Series.dt()) to obtain the time, that will be already in the desired format.

You can also use dt.strftime to format the output string which supports the same string format as the python standard library.

df['Datetime'] = pd.to_datetime(df.Datetime)

df['Date'] = df.Datetime.dt.strftime('%m/%d/%Y')
df['Time'] = df.Datetime.dt.time

print(df)
             Datetime        Date      Time
0 2020-10-27 14:28:28  10/27/2020  14:28:28
1 2020-08-02 03:30:18  08/02/2020  03:30:18
2 2020-06-15 17:38:19  06/15/2020  17:38:19
  •  Tags:  
  • Related