9

When saving timestamp in Django's DateTimeField using auto_now_add this way:

creation_timestamp = models.DateTimeField(auto_now_add=True)

the field is saved with miliseconds:

2018-11-20T15:58:44.767594-06:00

I want to format this to be displayed without miliseconds:

2018-11-20T15:58:44-06:00

But the only option I could come up with does not exactly show what I need:

format="%Y.%m.%dT%H:%M:%S%z" gives me 2018.11.20T15:58:44-0600 How do I format this field the way I need?

Alternatively I'd rather save DateTimeField without milliseconds at all but does auto_now_add allow to do this sort of thing?

Stan Reduta
  • 3,292
  • 5
  • 31
  • 55

4 Answers4

8

If you want to format it on when displaying it, you can use: creation_timestamp.strftime("%Y-%m-%d%H:%M:%S")

You can also make DateTimeField to save it in that format, but this would request a set of changes which will apply system wide:

In your settings file set the follwing:

  1. DATETIME_FORMAT="%Y-%m-%d%H:%M:%S"
  2. L10N=False to make sore localization data doesn't take precedent when it comes to dates format.
  3. USE_TZ=False

But, consider the fact that this changes will apply by default to all date time objects from your project.

Alex
  • 2,356
  • 15
  • 19
6

You can override DateTimeField's value_to_string method and add the changes there. For example:

class CustomDateTimeField(models.DateTimeField):
    def value_to_string(self, obj):
        val = self.value_from_object(obj)
        if val:
            val.replace(microsecond=0)
            return val.isoformat()
        return ''

And use it in model:

 created = CustomDateTimeField(auto_now_add=True)
ruddra
  • 50,746
  • 7
  • 78
  • 101
0

I think you will have to use isoformat. Look at that answer:

Show the : character in the timezone offset using datetime.strftime

Tiago Gomes
  • 357
  • 4
  • 12
0

I use pandas to_datetime() function to convert the time to string format.

import pandas as pd
record_list = myModel.objects.all()
for idx, record in enumerate(record_list ):
    st = str(pd.to_datetime(record.start_time))
    record_list[idx].start_time = st
Alex Fang
  • 79
  • 3