Python converting Django model.datetime from 24hr to AM/PM?
So I have this model field in Django that stores time in YYYY-MM-DD HH:MM:SS, here is how its created.
station_0_checked_time = models.DateTimeField(
null = True,
default = datetime.datetime(1970, 1, 1, 0, 0)
)
The data is stored properly as verified by the admin section of my Django site.
Station 0 Checked Time:
Date: 1970-01-01
Time: 22:00:10
However, when attempting to retrieve the data in a Django view with the following code I get the wrong output
#SUBCARD is the name of the model object
print(SUBCARD.station_0_checked_time)
Expected:
1970-01-01 22:00:10
Actual:
1970-01-02 06:00:10+00:00
I don't really understand the conversion that is happening here. Thank you for the help.
You just have to manually format it when you need to see it in the correct format
view.py
from datetime import datetime
print(SUBCARD.station_0_checked_time.strftime("%Y-%m-%d %H:%M:%S"))
Python strftime cheatsheet: https://strftime.org/
template.html
{{ SUBCARD.station_0_checked_time|date:'Y-m-d H:i:s' }}
Template Docs: https://docs.djangoproject.com/en/4.1/ref/templates/builtins/#date
You could also make it a Model method instead! - Probably my preferred method as it's all in one place
# models.py
class MyModel(models.Model):
station_0_checked_time = models.DateTimeField()
# other fields
def get_sation_o_checked_time(self):
from datetime import datetime
return self.station_0_checked_time.strftime("%Y-%m-%d %H:%M:%S")
##############################################
# Use in view.py
print(SUBCARD.get_station_0_checked_time())
# Use in template.html
{{ SUBCARD.get_station_0_checked_time }}