Python Forum

Full Version: How to extract only time from the date_time?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there,
I have follow column:
0 2017-05-29 18:36:27
1 2017-06-12 19:00:33
2 2017-02-13 17:02:02
3 2017-04-24 18:39:45
4 2017-01-26 15:36:07
5 2017-06-21 09:43:54
6 2017-04-24 08:33:31
7 2017-03-21 07:23:58
8 2017-01-14 12:16:20

From this column I want to extract the time in this format: hh:mm:msec

How can I do this in python3?

Here u can see my first try:

import pandas as pd

filename = 'chicago.csv'

# load data file into a dataframe
df = pd.read_csv('chicago.csv')
#print (df.head())

# convert the Start Time column to datetime
df1 = pd.to_datetime(df['Start Time']) 
print (df1)
The results see on the top: It gives me date_time column
Use:
datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S")
to convert your date (for example, 0 - '2017-05-29 18:36:27') to datetime format
λ python
Python 3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> x = '2017-05-29 18:36:27'
>>> z = datetime.datetime.strptime(x, "%Y-%m-%d %H:%M:%S")
>>>
then use strftime to reformat to hh:mm:ss
>>> ptime = z.strftime('%H:%M:%S')
>>> ptime
'18:36:27'
>>>
But the time is already in this format, so you could just strip off that part:
>>> ptime = x[11:]
>>> ptime
'18:36:27'
or if the index is part of the string:
>>> date = '8 2017-01-14 12:16:20'
>>> idx = date.rindex(' ')
>>> pdate = date[idx+1:]
>>> pdate
'12:16:20'
>>>