Converting Python time to another format

I need to convert the date string "2014-12-17 08: 00: 00.23" to the string "08:00:00" in python. I have looked at datetime.strptime but still can't find a way to do this. eg:

2014-12-17 08: 00: 00.23 - 08:00:00

what would be the template for the above time format.

+3


source to share


2 answers


Parse it first with strptime

, then format your datetime object with strftime

.

Docs



import datetime
t = '2014-12-17 08:00:00.23'
dt = datetime.datetime.strptime(t, '%Y-%m-%d %H:%M:%S.%f')
print dt.strftime('%H:%M:%S')
=> 08:00:00

      

+3


source


If your time string is of a fixed width, you can simply get the substring from the original time string:

In [90]: ts = '2014-12-17 08:00:00.23'

In [91]: ts[-11:-3]
Out[91]: '08:00:00'

      



If you want to get a datetime object, use datetime

either instead dateutil

:

In [99]: from dateutil import parser
    ...: dt = parser.parse(ts)
    ...: dt.strftime("%H:%M:%S")
Out[99]: '08:00:00'

      

0


source







All Articles