显示时间格式为(MM / DD / YYYY - HH:MM AM / PM) - Django / Python

时间:2015-03-17 21:41:23

标签: python django email datetime django-views

在" send_mail"功能,我想改变"开始"变量以在电子邮件中将日期/时间显示为MM / DD / YYYY - HH:MM AM / PM。有人知道怎么做吗?

提前谢谢!

date = coerce_date_dict(request.GET)
initial_data = None
if date:
    try:
        start = datetime.datetime(**date)
        initial_data = {
            "start": start,
            "end": start + datetime.timedelta(minutes=60)
        }
    except TypeError:
        raise Http404
    except ValueError:
        raise Http404

instance = None
if event_id is not None:
    instance = get_object_or_404(Event, id=event_id)

calendar = get_object_or_404(Calendar, slug=calendar_slug)

form = form_class(data=request.POST or None, instance=instance, initial=initial_data)

if form.is_valid():
    event = form.save(commit=False)
    if instance is None:
        event.creator = request.user
        event.calendar = calendar
        try:
            send_mail('New Lesson', '%s has scheduled a new lesson for %s' %(request.user.full_name, start), 'example@gmail.com', ['example@gmail.com'])
        except:
            pass
    event.save()
    next = next or reverse('event', args=[event.id])
    next = get_next_url(request, next)
    return HttpResponseRedirect(next)

1 个答案:

答案 0 :(得分:4)

startdatetime.datetime对象,因此我们可以调用其strftime方法生成格式化字符串。

您想要的格式说明符是%m/%d/%Y %I:%M %p

例如,当前时间(对我来说,在美国东海岸)调用的strftime方法生成:03/17/2015 05:51 PM

我们可以通过以下方式轻松集成到您的代码中:

start = datetime.datetime(**date)
initial_data = {
    "start": start.strftime("%m/%d/%Y %I:%M %p"),
    "end": start + datetime.timedelta(minutes=60)
}

注意:您必须确保进行此更改不会破坏其他任何“未来” - 因为initial_data['start'] datetime.datetime个对象,现在是一个字符串。