filiphl
filiphl

Reputation: 991

Unexpected datetime format in Django

I have a django project in which one of my models has a dateField named start_time. In my views.py I created a DetailView, and try to retrieve the timestamp like:

s = self.object.start_time.strftime('%d-%b-%Y')

On my Raspberry Pi, it gives the expected result.

print(s)
22-Nov-2018

However on my Ubuntu 18 computer it gives:

print(s)
22-nov.-2018

How can I get my Ubuntu machine to give the same (expected) result as the Raspberry Pi?

They both run Django 2.1.3.

Upvotes: 1

Views: 88

Answers (2)

filiphl
filiphl

Reputation: 991

What finally fixed my problem was to, on the computer giving unexpected results, add

export LC_ALL=en_US.UTF-8

to ~/.bashrc. Then open a new terminal or call source ~/.bashrc.

An alternative is to include

import locale
locale.setlocale(locale.LC_ALL, "en_US.UTF-8")

in views.py of the app.

You can check your current locale settings by calling locale from the terminal. In my case LC_ALL was blank.

Upvotes: 0

kungphu
kungphu

Reputation: 4849

The value %b is locale-dependent (see the relevant strftime doc).

Check the locale on both machines; it's likely they're at least subtly different. Ensuring both are using the same locale would be ideal in any case, but particularly for dates, you might consider sticking to locale-independent numerical values instead.

Upvotes: 1

Related Questions