简体   繁体   中英

Python time conversion to other format

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

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

what will be the pattern for the above time format.

First parse it using strptime , then format the datetime object using 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

If your time string is of fixed width, you can simply get the sub-string 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 or dateutil module instead:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM