Creating a custom Django DateTimeField model

In my last post I ran into a problem. A legacy database stores values as BigInt in MySQL using Unix time. Django uses datetime. I want the nice validation and widgets from Django’s DateTimeField. Here’s how to solve in.

Create a new field, I called it UnixTimestampField and overrode models.DateTimeField.

from django.db import models
from datetime import datetime
from time import strftime, mktime
import time

class UnixTimestampField(models.DateTimeField):
__metaclass__ = models.SubfieldBase

def __init__(self, null=False, blank=False, **kwargs):
super(UnixTimestampField, self).__init__(**kwargs)

def db_type(self):
typ=['bigint']
if self.isnull:
typ += ['NULL']
return ' '.join(typ)

def to_python(self, value):
super(UnixTimestampField, self)
try:
return datetime.fromtimestamp(float(value))
except:
return value

def get_db_prep_value(self, value):
if value==None:
return None
return time.mktime(value.timetuple())

def get_prep_value(self, value):
if value==None:
return None
return time.mktime(value.timetuple())

It seems to work. I’ll update though if I run into any trouble down the line or re-factor it. This is my first attempt at making a custom Django Model Field.

By David

I am a supporter of free software and run Burke Software and Consulting LLC. I am always looking for contract work especially for non-profits and open source projects. Open Source Contributions I maintain a number of Django related projects including GlitchTip, Passit, and django-report-builder. You can view my work on gitlab. Academic papers Incorporating Gaming in Software Engineering Projects: Case of RMU Monopoly in the Journal of Systemics, Cybernetics and Informatics (2008)

1 comment

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: