Because you are dealing with a datetime object already, you are getting this error because strptime
requires a string and not a Timestamp
object. From the definition of strptime
:
def strptime(cls, date_string, format):
'string, format -> new datetime parsed from a string (like time.strptime()).'
What you are actually looking to do is first convert your datetime to the format you require in to a string using strftime
:
def strftime(self, format):
"""Return a string representing the date and time, controlled by an
explicit format string.
and then bring it back to a datetime
object using strptime
. The following demo will demonstrate. Note the use of .date()
at the end in order to remove the unneeded 00:00:00
time portion.
>>> from datetime import datetime
>>> orig_datetime_obj = datetime.strptime("2015/10/31", '%Y/%m/%d').date()
>>> print(orig_datetime_obj)
2015-10-31
>>> print(type(orig_datetime_obj))
<type 'datetime.datetime'>
>>> new_datetime_obj = datetime.strptime(orig_datetime_obj.strftime('%d-%m-%y'), '%d-%m-%y').date()
>>> print(new_datetime_obj)
2015-10-31
>>> print(type(new_datetime_obj))
<type 'datetime.date'>
Alternatively, if all you require is just converting it to a different format but in a string, you can simply stick to just using strftime
with your new format. Using my example above, you would only need this portion:
orig_datetime_obj.strftime('%d-%m-%y')