Converting python string to datetime obj with AM/PM

前端 未结 1 1257
野趣味
野趣味 2021-01-18 13:26

easy problem but this is bugging me:

Say I have a string like this:

test = \'2015-08-12 13:07:32\'

To convert it into a datetime ob

1条回答
  •  -上瘾入骨i
    2021-01-18 14:12

    datetime.strptime() is used for converting a string to a datetime object , when using strptime() you have to specify the correct format in which the date/time in the string exists .

    In your case the format should be - '%Y-%m-%d %H:%M:%S' .

    Example -

    >>> test = '2015-08-12 13:07:32'
    >>> import datetime
    >>> datetime.datetime.strptime(test, '%Y-%m-%d %H:%M:%S')
    datetime.datetime(2015, 8, 12, 13, 7, 32)
    

    If what you really want is the date-time back as a string with the AM/PM , then you need to use strftime() to convert it back to string with the format you want, in this case the format would be - '%Y-%m-%d %I:%M:%S %p' . Example -

    >>> datetime.datetime.strptime(test, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%d %I:%M:%S %p')
    '2015-08-12 01:07:32 PM'
    

    datetime objects internally do not store (and do not have to store) the AM/PM information, since that can be easily calculated from the hour.

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