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?
#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


Messages In This Thread
RE: How to extract only time from the date_time? - by Larz60+ - May-11-2018, 01:42 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Iterate through dataframe to extract delta of a particular time period lynnette1983 1 1,663 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