Convert 12 hour time string into datetime or time

前端 未结 3 678
暗喜
暗喜 2021-01-16 08:03

Ive been trying to use time.strptime(string1,\'%H:%M\'), with no success

How can I get the following:

Input     Output
3:14AM  -> 03:         


        
相关标签:
3条回答
  • 2021-01-16 08:21

    You're missing %p (Locale’s equivalent of either AM or PM).

    time.strptime(string1,'%H:%M%p')
    
    0 讨论(0)
  • 2021-01-16 08:22

    Use %I for 12 hour times and %p for the am or pm as follows:

    from datetime import datetime
     
    for t in ["3:14AM", "9:33PM", "12:21AM", "12:15PM"]:
        print(datetime.strptime(t, '%I:%M%p').strftime("%H:%M"))
    

    Giving you the following output:

    03:14
    21:33
    00:21
    12:15 
        
    

    The formats used are documented in strftime() and strptime() Behavior

    0 讨论(0)
  • 2021-01-16 08:32

    The problem requires that you first strptime using %I for the 12 hour time and adding the directive %p for AM or PM to get a time object; altogther '%I:%M%p'. Then use strftime to format the time object into a string:


    Trials:

    >>> tm = time.strptime('12:33AM', '%I:%M%p')
    >>> time.strftime('%H:%M', tm)
    '00:33'
    >>> tm = time.strptime('9:33PM', '%H:%M%p')
    >>> time.strftime('%H:%M', tm)
    '09:33'
    

    Doc reference: https://docs.python.org/2/library/time.html

    0 讨论(0)
提交回复
热议问题