Python Forum
How to extract only time from the date_time?
Thread Rating:
  • 1 Vote(s) - 4 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to extract only time from the date_time?
#1
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
Reply
#2
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'
>>>
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Iterate through dataframe to extract delta of a particular time period lynnette1983 1 1,625 Oct-22-2020, 12:19 AM
Last Post: scidam

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020