Convert time string into all date or datetime field format in Django

Convert time string into all date or datetime field format in Django

I will guide you how to convert string that contain time into datetime that will stored into DateField() / DateTimeField() format in Django. For introduction, here are format for DateField() and DateTimeField that you can read all rest in here.

For DateField() :

1
2
3
4
5
'%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', # '2006-10-25', '10/25/2006', '10/25/06'
'%b %d %Y', '%b %d, %Y',            # 'Oct 25 2006', 'Oct 25, 2006'
'%d %b %Y', '%d %b, %Y',            # '25 Oct 2006', '25 Oct, 2006'
'%B %d %Y', '%B %d, %Y',            # 'October 25 2006', 'October 25, 2006'
'%d %B %Y', '%d %B, %Y',            # '25 October 2006', '25 October, 2006'

For DateTimeField():

1
2
3
4
5
6
7
8
9
'%Y-%m-%d %H:%M:%S',     # '2006-10-25 14:30:59'
'%Y-%m-%d %H:%M',        # '2006-10-25 14:30'
'%Y-%m-%d',              # '2006-10-25'
'%m/%d/%Y %H:%M:%S',     # '10/25/2006 14:30:59'
'%m/%d/%Y %H:%M',        # '10/25/2006 14:30'
'%m/%d/%Y',              # '10/25/2006'
'%m/%d/%y %H:%M:%S',     # '10/25/06 14:30:59'
'%m/%d/%y %H:%M',        # '10/25/06 14:30'
'%m/%d/%y',              # '10/25/06'

Basically what we need to convert string into datetime, first we must arrange it format using time.strptime with proper format. Then we convert into mktime and pass into datetime objects.

So, you must import two modules here before start :

1
2
import time
from datetime import datetime

Let start with cases :

“01JAN12”
Give date with day, month and year format.

1
2
3
time_string = "01JAN12"
strp_time = time.strptime(time_string, "%d%b%y")
date_django = datetime.fromtimestamp(time.mktime(strp_time))

“01/21/2012 14:30:59”
Give datetime.

1
2
3
time_string = "01/21/2012 14:30:59"
strp_time = time.strptime(time_string, "%m/%d/%Y %H:%M:%S")
date_django = datetime.fromtimestamp(time.mktime(strp_time))

Easy right? Now you can convert all string format and pass into datetime object into Django models 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *