Skip to content
Advertisement

Converting datetime only to time in pandas

I would like to ask a question regarding converting datetime only to time. I have values ‘Date Created” that include Dates and Times in one column and I would like to create two columns: one with only Date and one with Time. I wrote a code but in Time column I got a default date of 1900-01-01 along with time.

I wonder now how I could create a column only with Time in format: Hours:Minutes:Seconds

I will be grateful for any tips.

    Date Created      Date         Time
2016-02-20 09:26:45 2016-02-20  1900-01-01 09:26:45
2016-02-19 19:30:25 2016-02-19  1900-01-01 19:30:25
2016-02-19 18:13:39 2016-02-19  1900-01-01 18:13:39
2016-03-01 14:15:36 2016-03-01  1900-01-01 14:15:36
2016-03-04 14:47:57 2016-03-04  1900-01-01 14:47:57

I wrote a code like the one below to extract dat

Data.loc[:,'Date Created'] = pd.to_datetime(Data.loc[:,'Date Created'], format="%Y-%m-%d %H:%M:%S")
Data.loc[:,'Date'] = pd.to_datetime(Data.loc[:,'Date'], format="%Y-%m-%d")
Data.loc[:,'Time'] = pd.to_datetime(Data.loc[:,'Time'], format="%H:%M:%S")

Advertisement

Answer

pandas has no separate datatypes for date and time. if you only want your columns to show date or time resp., you could format to string (strftime). Ex:

import pandas as pd

Data = pd.DataFrame({'Date Created': ["2016-02-20 09:26:45", "2016-02-19 19:30:25", "2016-02-19 18:13:39"]})

Data['Date Created'] = pd.to_datetime(Data['Date Created'])
Data['Date'] = Data['Date Created'].dt.strftime("%Y-%m-%d")
Data['Time'] = Data['Date Created'].dt.strftime("%H:%M:%S")

Data
         Date Created        Date      Time
0 2016-02-20 09:26:45  2016-02-20  09:26:45
1 2016-02-19 19:30:25  2016-02-19  19:30:25
2 2016-02-19 18:13:39  2016-02-19  18:13:39

Python documentation / strftime

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement