Login

Parse datetime model field to string

Author:
jzelez
Posted:
July 3, 2010
Language:
Python
Version:
1.2
Tags:
datetime string parse
Score:
0 (after 0 ratings)

Checks the type of the field (date / time / date-time) and returns corresponding value as a string.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def convertDatetimeToString(o):
	DATE_FORMAT = "%Y-%m-%d" 
	TIME_FORMAT = "%H:%M:%S"

	if isinstance(o, datetime.date):
	    return o.strftime(DATE_FORMAT)
	elif isinstance(o, datetime.time):
	    return o.strftime(TIME_FORMAT)
	elif isinstance(o, datetime.datetime):
	    return o.strftime("%s %s" % (DATE_FORMAT, TIME_FORMAT))

More like this

  1. Natural language date/time form fields by jdriscoll 8 years ago
  2. TodayDateTimeField by leotr 7 years, 2 months ago
  3. Encoding datetime for JSON consumers like YUI by acdha 5 years, 6 months ago
  4. Template-Filter for Feedparser-Dates by kioopi 6 years ago
  5. Querying datetime aware objects in your local timezone by jayliew 3 years, 1 month ago

Comments

bolso103 (on November 3, 2011):

Hello,

I am using the function, but I do not know why isinstance(o, datetime.time) is returning false, when it should be true. My model has a DateTimeField attribute:

-----------------------------------------------------

class Measure (models.Model):

    power = models.IntegerField()               
date = models.DateTimeField('measure date')     
machine = models.ForeignKey(Machine)

def __unicode__(self):
    return self.machine.name

----------------------------------------------------

On the shell:

date=Measure.objects.get(id=4).date

print date

2011-11-01 01:18:27

conv = convertDatetimeToString(Measure.objects.get(id=4).date)

print conv

2011-11-01

#

hobs (on January 17, 2013):

You put .date rather than .datetime after the field which converts the datetime.datetime object (a DateTimeField in your db) into a datetime.date object. A date object doesn't contain time information and it doesn't inherit the datetime class, so the isinstance doesn't match datetime.datetime. Try doing type(obj) whenever you want to know what type an object is.

#

Please login first before commenting.