James L.
James L.

Reputation: 1153

Django 1.6 format datetime in views

I've a booking form in my template that sends an email when it's submitted. In my database the datetime field is shown like: Oct. 6, 2015, 3:58 p.m. But when I get the email the datetime field is shown like: 2015-10-06 15:58:50.954102 How do i format it such that in the email it's shown exactly like how it's shown in the database?

models.py

class Booking(models.Model):
    patient_name = models.CharField(max_length=1300)
    phone = models.IntegerField(null=True, blank = True)
    preference = models.CharField(max_length=150,null = True, blank = True) #morning,noon,night
    doctor = models.ForeignKey(Doctor)
    clinic = models.ForeignKey(Clinic,null=True, blank = True)
    datetime = models.DateTimeField(auto_now=True, auto_now_add=True, blank = True, null = True)


    def __unicode__(self):
        return u"%s %s" % (self.patient_name, self.doctor)

views.py

 lead = Booking(doctor_id=doctor.id, clinic_id=doctor.clinic.id, preference=preference, patient_name=patient_name, phone=phone)
 lead.save()
 body = "Request Made: " + str(lead.datetime) +" "
 email = EmailMessage('Blah', body, to=[clinic.email])
 email.send()

Upvotes: 1

Views: 1671

Answers (2)

Alasdair
Alasdair

Reputation: 308869

You can format datestrings using strftime

>>> from datetime import date
>>> dt = date(2015, 10, 6, 15, 58, 50)
>>> dt.strftime("%b. %-d %Y %-I:%M %p")
'Oct. 6 2015 2:12 PM'

There's a list of the codes for strftime at at http://strftime.org/

So in your view you would do something like

body = "Request Made: %s " % lead.datetime.strftime("%b. %-d %Y %-I:%M %p")

Upvotes: 3

user1797792
user1797792

Reputation: 1189

Thats not exactly how it's in the database, it's just what the tool you use to view inside the database, displays datetime.

However if you want your datetime to look exactly like that, use:

lead.datetime.strftime("%b. %-d %Y %-I:%M %p")

Here are some relevant sources: https://docs.python.org/2/library/datetime.html#datetime.datetime https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

Upvotes: 2

Related Questions