Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting UNIX time to datetime object in Jinja templates

I want to convert my timestamp to datetime in jinja2..

here's my sample code:

import time

date = time.time()
self.tv['date'] = date

sample html:

<p>{{ date }}</p>

I want to convert it to datetime using jinja2 in python..

thanks..

like image 810
Leonard Mark Avatar asked Mar 01 '13 02:03

Leonard Mark


People also ask

How do I convert a timestamp to a DateTime?

Timestamp to DateTime object You can simply use the fromtimestamp function from the DateTime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding DateTime object to timestamp.

Is Jinja2 dynamic?

Jinja supports dynamic inheritance and does not distinguish between parent and child template as long as no extends tag is visited.

What is Jinja2 syntax?

What is Jinja 2? Jinja2 is a modern day templating language for Python developers. It was made after Django's template. It is used to create HTML, XML or other markup formats that are returned to the user via an HTTP request.


2 Answers

Make a custom filter like

@app.template_filter('ctime')
def timectime(s):
    return time.ctime(s) # datetime.datetime.fromtimestamp(s)

And use your template filter

{{ date | ctime }}
like image 185
KyungHoon Kim Avatar answered Nov 15 '22 15:11

KyungHoon Kim


You convert it before passing it to a template, eg:

>>> import time
>>> date = time.time()
>>> from datetime import datetime
>>> datetime.fromtimestamp(date)
datetime.datetime(2013, 3, 1, 2, 57, 29, 472572)

And optionally use formatting:

>>> format(datetime.fromtimestamp(date), '%Y%m%d')
'20130301'
like image 38
Jon Clements Avatar answered Nov 15 '22 14:11

Jon Clements