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"

1
  • Hello and welcome to SO! Please show a code attempt and what you passed into strptime. There are a couple different things to consider Commented Nov 4, 2022 at 13:57

2 Answers 2

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 
Sign up to request clarification or add additional context in comments.

2 Comments

my input is in 24 hour string format
Then I believe just do the reverse (in_time - out_time
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") 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.