How to format string time object with python?

Viewed 73

I am using django python. Now I want to convert the following timing string into hours, minutes ,am/pm format.

string_time = '2022-09-13 11:00:00.996795+00'

expected output:

11:00 am

actual output is :

ValueError: time data '2022-09-13 11:00:00.996795+00' does not match format '%m/%d/%y %H:%M:%S'

my code :

 def time_slots(self,string_time='2022-09-13 11:00:00.996795+00'):
        print(datetime.strptime(string_time, '%m/%d/%y %H:%M:%S'),type(start_time))
        start_time = datetime.strptime(string_time, '%m/%d/%y %H:%M:%S')
        return formated_start_time
3 Answers

You can use the parse function provided by dateutil:

from dateutil import parse
string_time = '2022-09-13 11:00:00.996795+00'
dt = parse(string_time)
return dt.strftime("%H:%M %p")

Result: 11:00 AM

When you remove the last three chars ('+00') and replace the space with T you can use datetime.datetime.fromisoformat(str) to get a datetime object.

from datetime import datetime
timestr = '2022-09-13 11:00:00.996795+00'
timestr = timestr.rstrip(timestr[-3:]).replace(' ', 'T')
date = datetime.fromisoformat(timestr)

from there you can use date.hour and date.minute to get the values you want. e.g.:

hour = date.hour%12
minute = date.minute
addition = ''
if date.hour > 12:
    addition = 'pm'
else:
    addition = 'am'
print(f'{hour}:{minute} {addition}')

I'm not sure if the last string +00 is useful. If not, the following implementation can help you.

from datetime import datetime

def time_slots(string_time='2022-09-13 11:00:00.996795+00'):
  date = datetime.strptime(string_time[:-3], '%Y-%m-%d %H:%M:%S.%f')
  return date.strftime("%H:%M %p")
output = time_slots()
print(output) # the output is: 11:00 AM
Related