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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With