time conversion in python code example

Example 1: how to convert a am pm string to 24 hrs time python

a=''
def timeConversion(s):
   if s[-2:] == "AM" :
      if s[:2] == '12':
          a = str('00' + s[2:8])
      else:
          a = s[:-2]
   else:
      if s[:2] == '12':
          a = s[:-2]
      else:
          a = str(int(s[:2]) + 12) + s[2:8]
   return a


s = '11:05:45AM'
result = timeConversion(s)
print(result)

Example 2: how to convert a am pm string to 24 hrs time python

>>> from datetime import *
>>> m2 = '1:35 PM'
>>> m2 = datetime.strptime(m2, '%I:%M %p')
>>> print(m2)
1900-01-01 13:35:00

Example 3: time format conversion in python

import datetime

date_time_str = '2018-06-29 08:15:27.243860'
date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f')

print('Date:', date_time_obj.date())
print('Time:', date_time_obj.time())
print('Date-time:', date_time_obj)