I need datetime object in the format mm/dd/yyyy. I tried using strptime
:
datetime.strptime("05-08-2022","%d-%m-%Y")
>>datetime.datetime(2022, 8, 5, 0, 0)
That changes the format to YYYY/MM/DD.
I know we can change the format using strftime
to convert datetime to any format but that results into a string object. I would like retain it as datetime object along with format mm/dd/yyyy.
Another thing, I have tried is to set the locale to french datetime format (mm/dd/yyyy Link):
locale.setlocale(locale.LC_TIME, 'fr_FR.UTF-8'))
datetime.strptime("05-08-2022","%d-%m-%Y")
>>datetime.datetime(2022, 8, 5, 0, 0)
However, that did not work either. Are there any other way to convert 'strings or dates' to datetime objects maintaining the format mm/dd/yyyy.
CodePudding user response:
As I said in my comment, you'll need to create a new class and specify your own __repr__
method.
import datetime
class DateTime:
def __init__(self, datetime_instance):
self.datetime = datetime_instance
def __repr__(self):
return f"datetime.datetime({self.datetime.month}, {self.datetime.day}, {self.datetime.year})"
a = datetime.datetime(year=2000, month=12, day=15)
b = DateTime(a)
Output for a
:
a
>>datetime.datetime(2000, 12, 15, 0, 0)
Output for b
:
b
>>datetime.datetime(12, 15, 2000)