Converting python string to datetime obj with AM/PM

Question:

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 object and change it to AM/PM specification, shouldn’t this work?

datetime.datetime.strptime(test, '%Y-%m-%d %I:%M:%S %p')

I’m getting an error like this:
ValueError: time data '2015-08-12 13:07:32' does not match format '%Y-%m-%d %I:%M:%S %p'

Also, for bonus points:

If I already have something in datetime format, how do I change it from that state? (if I wanted to keep it as a datetime object but just reformat it to make it AM/PM)

Asked By: SpicyClubSauce

||

Answers:

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.

Answered By: Anand S Kumar
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.