Opened 6 years ago

Closed 6 years ago

#18951 closed Bug (fixed)

Datetime microseconds cutoff first zero in Django templates

Reported by: olofom@… Owned by: Aymeric Augustin
Component: Template system Version: 1.4
Severity: Normal Keywords: datetime microseconds
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


So I had a datetime object that I wanted to display on a web page and then post back through a hidden field. This didn't work (unless I use the 'c' flag with the date filter to get the ISO format, then it works fine).

>>> datetime.datetime(2013, 9, 12, 9, 24, 16, 14070)
datetime.datetime(2013, 9, 12, 9, 24, 16, 14070)
>>> str(datetime.datetime(2013, 9, 12, 9, 24, 16, 14070))
'2013-09-12 09:24:16.014070'

BUT {{ timestamp|date:'Y-m-d H:i:s.u' }} prints:
2013-09-12 09:24:16.14070
without the first zero. Then when trying to convert this back to a datetime object I get:

>>> datetime.datetime.strptime('2013-09-12 09:24:16.14070', "%Y-%m-%d %H:%M:%S.%f")
datetime.datetime(2013, 9, 12, 9, 24, 16, 140700)
>>> str(datetime.datetime.strptime('2013-09-12 09:24:16.14070', "%Y-%m-%d %H:%M:%S.%f"))
'2013-09-12 09:24:16.140700'

So in the end I ended up with the microseconds: 140700 instead of 014070, but the real bug is that the 'u' flag of date prints 14070 instead of 014070.

Change History (4)

comment:1 Changed 6 years ago by Karen Tracey

Triage Stage: UnreviewedAccepted

comment:2 Changed 6 years ago by Aymeric Augustin

Owner: changed from nobody to Aymeric Augustin

comment:3 Changed 6 years ago by Aymeric Augustin

Technically, this is the documented behavior. says:

u Microseconds. 0 to 999999

and not:

u Microseconds. 000000 to 999999

That said, it isn't a very useful behavior :)

Django's dateformat mimicks PHP's date. I just checked that PHP left-pads the result with zeros.

I think it's just a bug that dates back to 2005, and I'm going to commit a fix shortly.

comment:4 Changed 6 years ago by Aymeric Augustin <aymeric.augustin@…>

Resolution: fixed
Status: newclosed

In 822cfce3df53301d9f9f4c14bd8a0cb2a1956e2e:

Fixed #18951 -- Formatting of microseconds.

Thanks olofom at gmail com for the report.

Note: See TracTickets for help on using tickets.
Back to Top