Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert 12 hour into 24 hour times

Tags:

I'm trying to convert times from 12 hour times into 24 hour times...

Automatic Example times:

06:35  ## Morning
11:35  ## Morning (If m2 is anywhere between 10:00 and 12:00 (morning to mid-day) during the times of 10:00 and 13:00 (1pm) then the m2 time is a morning time)
1:35  ## Afternoon
11:35  ## Afternoon

Example code:

m2 = "1:35" ## This is in the afternoon.
m2 = datetime.strptime(m2, "%H:%M")
print m2

Expected Output:

13:35

Actual Output:

1900-01-01 01:35:00

I tried a second variation but again didn't help :/

m2 = "1:35" ## This is in the afternoon.
m2split = m2.split(":")
if len(m2split[0]) == 1:
    m2 = ("""%s%s%s%s""" % ("0", m2split[0], ":", m2split[1]))
    print m2
m2temp = datetime.strptime(m2, "%I:%M")
m2 = m2temp.strftime("%H:%M")

What am I doing wrong and how can I fix this?

like image 683
Ryflex Avatar asked Oct 07 '13 15:10

Ryflex


1 Answers

This approach uses strptime and strftime with format directives as per https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior, %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
like image 58
modpy Avatar answered Sep 23 '22 16:09

modpy