2015-10-06 33 views
1

我的模板中有一個預訂表單,它在提交時發送一封電子郵件。在我的數據庫中,datetime字段顯示爲:Oct. 6, 2015, 3:58 p.m.但是,當我收到電子郵件時,datetime字段顯示爲:2015-10-06 15:58:50.954102如何格式化它,以便在電子郵件中顯示與數據庫中顯示的完全相同的內容?視圖中的Django 1.6格式日期時間

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() 

回答

2

可以使用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' 

有在爲strftime代碼的列表格式datestrings在http://strftime.org/

那麼在你看來,你會做這樣的事情

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