0

The time is given in string for eg "23:20". However in my function I need to compare times for which I gotta convert these to time format

I tried strptime() and it works with 12 hour format for eg when I enter "12:00PM"

  • Hello and welcome to SO! Please show a code attempt and what you passed into `strptime`. There are a couple different things to consider – StonedTensor Nov 04 '22 at 13:57

2 Answers2

1

Possible Duplicate of [https://stackoverflow.com/questions/19229190/how-to-convert-am-pm-timestmap-into-24hs-format-in-python]

Code that works from there

%H is the 24 hour clock, %I is the 12 hour clock and when using the 12 hour clock, %p qualifies if it is AM or PM.

   from datetime import datetime
   m2 = '1:35 PM'
   in_time = datetime.strptime(m2, "%I:%M %p")
   out_time = datetime.strftime(in_time, "%H:%M")
   print(out_time)
   13:35
Aarav Shah
  • 55
  • 1
  • 7
0

For converting 24 hour format to a datetime.time object you need to use the %H (hours in 24h format) and %M (minutes) format:

import datetime as dt

string_time = "23:20"
out_time = dt.datetime.strptime(string_time, r"%H:%M")
Matteo Zanoni
  • 3,429
  • 9
  • 27