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.
JavaScript
x
7
1
Date Created Date Time
2
2016-02-20 09:26:45 2016-02-20 1900-01-01 09:26:45
3
2016-02-19 19:30:25 2016-02-19 1900-01-01 19:30:25
4
2016-02-19 18:13:39 2016-02-19 1900-01-01 18:13:39
5
2016-03-01 14:15:36 2016-03-01 1900-01-01 14:15:36
6
2016-03-04 14:47:57 2016-03-04 1900-01-01 14:47:57
7
I wrote a code like the one below to extract dat
JavaScript
1
4
1
Data.loc[:,'Date Created'] = pd.to_datetime(Data.loc[:,'Date Created'], format="%Y-%m-%d %H:%M:%S")
2
Data.loc[:,'Date'] = pd.to_datetime(Data.loc[:,'Date'], format="%Y-%m-%d")
3
Data.loc[:,'Time'] = pd.to_datetime(Data.loc[:,'Time'], format="%H:%M:%S")
4
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:
JavaScript
1
14
14
1
import pandas as pd
2
3
Data = pd.DataFrame({'Date Created': ["2016-02-20 09:26:45", "2016-02-19 19:30:25", "2016-02-19 18:13:39"]})
4
5
Data['Date Created'] = pd.to_datetime(Data['Date Created'])
6
Data['Date'] = Data['Date Created'].dt.strftime("%Y-%m-%d")
7
Data['Time'] = Data['Date Created'].dt.strftime("%H:%M:%S")
8
9
Data
10
Date Created Date Time
11
0 2016-02-20 09:26:45 2016-02-20 09:26:45
12
1 2016-02-19 19:30:25 2016-02-19 19:30:25
13
2 2016-02-19 18:13:39 2016-02-19 18:13:39
14