Reputation: 17
I'm passing date directly from JSON to a template, but I cannot modify how it should be displayed. I'd like to display DD.MM.YYYY but it displays directly from JSON format (2020-08-05T00:00:00) I've tried using a custom filter but it gives a bunch of errors.
Edit JSON
"startDate": "2020-07-07T00:00:00"
app.py
@app.route('/generate', methods=['POST'])
def generate_pdf():
return render_to_pdf(request.json)
def render_to_pdf(context_dict):
templateLoader = jinja2.FileSystemLoader(searchpath="./templates/")
templateEnv = jinja2.Environment(loader=templateLoader)
TEMPLATE_FILE = "pdf_template.html"
template = templateEnv.get_template(TEMPLATE_FILE)
html = template.render(context_dict)
Upvotes: 1
Views: 1103
Reputation: 1627
strftime converts a date object into a string by specifying a format you want to use
you can do
now = datetime.now() # <- datetime object
now_string = now.strftime('%d.%m.%Y')
however, if you already converted your datetime object into a string (or getting strings from an api or something), you can convert the string back to a datetime object using strptime
date_string = '2020-08-05T00:00:00'
date_obj = strptime(date_string, '%Y-%m-%dT%H:%M:%S') # <- the format the string is currently in
You can first to strptime and then strftime directly from that to effectively convert a string into a different string, but you should avoid this if possible
converted_string = strptime(original_string, 'old_format').strftime('new_format')
This topic may be confusing because when you print(now) (remember, the datetime object), python automatically "represents" this and converts it into a string. however, it isnt actually a string at this time, but rather a datetime object. python can't print that, so it converts it - but you wont be able to jsonify this directly, for example.
Upvotes: 0