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
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.