Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django DateTimeField showing up as string

Hi one of my Django models has a the following field

created_at = models.DateTimeField(blank=True,null=True)

However when I check the data type it shows as String

 print(self.created_at)
 print(type(self.created_at))

2018-01-10T20:53:19Z
<class 'str'>

Funny thing is the same code running on my production server shows it as

2016-04-21 09:38:38+00:00
<class 'datetime.datetime'>

I am using python3 and Django 1.10.6.

Any idea what is causing this ?

like image 866
Dhanushka Amarakoon Avatar asked Oct 16 '25 01:10

Dhanushka Amarakoon


1 Answers

Databases don't store Python data types, so the django ORM does some transforming and casting for you to return you an equivalent Python type.

For example, DateField fields use a Python datetime object to store data. Databases don’t store datetime objects, so the field value must be converted into an ISO-compliant date string for insertion into the database.

(From the documentation on the save() method)

This only works if there is already data to be read from that particular field.

In other words, if you are creating a new record, the value will be a string because there is no existing value to the field.

If the object is being updated, then the value will be an date time object if you haven't updated that field.

Django uses the same save() method for creating new records and updating existing records.

like image 85
Burhan Khalid Avatar answered Oct 18 '25 15:10

Burhan Khalid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!