Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Converting datetime format maintaining the datetime data type in python

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):

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading