Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 879325
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T11:54:48+00:00 2026-05-15T11:54:48+00:00

Can I change the default __str__() function of the datetime.datetime object? By default, it

  • 0

Can I change the default __str__() function of the datetime.datetime object?
By default, it returns something like '2010-06-28 12:43:56.985790', and i need it to print something like '2010-06-28T12:44:21.241228'(which is the isoformat() function).

I need this for JSON serializing of a django model.

My model is:


class Transport(models.Model):
    user = models.ForeignKey(User)
    source = models.ForeignKey(Marker, related_name="source_marker")
    destination = models.ForeignKey(Marker, related_name="destination_marker")
    object = models.CharField(choices=possesion_choices, max_length=2**6)
    quantity = models.IntegerField()
    time_sent = models.DateTimeField()
    time_arrived = models.DateTimeField()

And when i serialize it (using the wadofstuff module), it prints something like


print serializers.serialize('json', Transport.objects.all(), relations=('source', 'destination',)  indent=4)
[
    {
        "pk": 1, 
        "model": "main.transport", 
        "fields": {
            [.. bla bla ..]
            "time_sent": "2010-06-28 12:18:05", 
            "time_arrived": "2010-06-28 12:38:36", 
            [.. bla bla ..]
        }
    }
]

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T11:54:49+00:00Added an answer on May 15, 2026 at 11:54 am

    Django uses a field’s value_to_string method to provide the string representation within a serializer. So you could define a custom field subclass that overrides this method:

    class MyDateTimeField(DateTimeField)
        def value_to_string(self, obj):
            val = self._get_val_from_obj(obj)
            if val is None:
                data = ''
            else:
                data = val.isoformat()
            return data
    

    Edited

    Aargh, looks like I was looking in completely the wrong place. The serializers.python.Serializer.handle_field method actually checks for date-time fields and passes them through unchanged to the JSON encoder. So it’s that encoder that we actually need to override.

    class MyJSONEncoder(DjangoJSONEncoder):
        def default(self, o):
            if isinstance(o, datetime.datetime):
                return o.isoformat()
            else:
                return super(MyJSONEncoder, self).default(o)
    

    Unfortunately, wadofstuff hardcodes the original DjangoJSONEncoder, so we’ll need to override the serializer too.

    from wadofstuff.django.serializers.json import Serializer
    class BetterSerializer(Serializer):
        """
        Convert a queryset to JSON.
        """
        def end_serialization(self):
            """Output a JSON encoded queryset."""
            self.options.pop('stream', None)
            self.options.pop('fields', None)
            self.options.pop('excludes', None)
            self.options.pop('relations', None)
            self.options.pop('extras', None)
            simplejson.dump(self.objects, self.stream, cls=MyJSONEncoder,
                **self.options)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 539k
  • Answers 539k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Getting right memory usage is trickier than one may think.… May 17, 2026 at 2:15 am
  • Editorial Team
    Editorial Team added an answer Try to call both things asynchronously. I.e. first change background… May 17, 2026 at 2:15 am
  • Editorial Team
    Editorial Team added an answer For me this setting is saved in a .csproj.resharper file.… May 17, 2026 at 2:15 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

Is any one knows how can i change the default (light blue) skin of
MySQL ResultSets are by default retrieved completely from the server before any work can
I want to know how we can change the navigation bar title of UIImagePickerController.
OK - Python newbie here - I assume I am doing something really stupid,
I've constructed a form, but some rows of the form can potentially be returned
I use PHP to access MySQL in XAMPP. My question is where I can
how can I edit the taxonomy view ? I'm talking about the view that
How can I omit all XML-Namespaces from the xslt in the html-output? My XSL
I have a custom control called TextBoxWithLabelAndUnits . From the name, you can tell
I'm trying to convert a standard SQL query to a LINQ to SQL query.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.