jph
jph

Reputation: 367

Display time format as (MM/DD/YYYY - HH:MM AM/PM) - Django/Python

Under the "send_mail" function, I would like to change the "start" variable to display the date/time as MM/DD/YYYY - HH:MM AM/PM in the email. Does someone know how to do this?

Thank you in advance!

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), '[email protected]', ['[email protected]'])
        except:
            pass
    event.save()
    next = next or reverse('event', args=[event.id])
    next = get_next_url(request, next)
    return HttpResponseRedirect(next)

Upvotes: 0

Views: 11561

Answers (1)

jedwards
jedwards

Reputation: 30210

start is a datetime.datetime object, so we can call its strftime method to generate a formatted string.

The format specifier you want is %m/%d/%Y %I:%M %p

For example, the strftime method called on the current time (for me, on the East Coast of US) generated: 03/17/2015 05:51 PM

Which we can easily integrate into your code with:

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

Note: You'll have to ensure that making this change doesn't break anything else "down the road" -- as initial_data['start'] was a datetime.datetime object, and is now a string.

Upvotes: 6

Related Questions