Use the datetime module's strptime()
to read the string as a datetime object and then convert it back to string using strftime()
, example -
>>> datetime.datetime.strptime('3:5','%H:%M').strftime('%I:%M %p')
'03:05 AM'
>>> datetime.datetime.strptime('18:30','%H:%M').strftime('%I:%M %p')
'06:30 PM'
>>> datetime.datetime.strptime('00:00','%H:%M').strftime('%I:%M %p')
'12:00 AM'
The formats explained -
%H - Hour (24-hour fomrat)
%M - Minute
%I - Hour (12-hour format)
%p - AM or PM
Function would look like -
def timeConvert():
import datetime
ds = input("Enter a time in hh:mm (military) format: ")
newds = datetime.datetime.strptime(ds, ,'%H:%M').strftime('%I:%M %p')
print(newds)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…