6

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)

SpicyClubSauce
  • 4,076
  • 13
  • 37
  • 62
  • Do you want the string with AM/PM back? Datetime objects do not as such have to store that information , since the date internally is stored in a different representation. – Anand S Kumar Aug 12 '15 at 04:00
  • are you saying datetime objects can't be represented in AM/PM format? Am i misreading this post? (http://stackoverflow.com/questions/1759455/how-can-i-account-for-period-am-pm-with-datetime-strptime) – SpicyClubSauce Aug 12 '15 at 04:02
  • No, what I am saying is `strptime()` is used for convert string to datetime object, you need to specify the format in which the date exists in the string, not the format in which you want it back. Datetime can easily calculate the AM/PM for the hour. – Anand S Kumar Aug 12 '15 at 04:05

1 Answers1

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.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176