Bootstrap FreeKB - Jinja - Date and Time
Jinja - Date and Time

Updated:   |  Jinja articles

now can be used to return the current date and time.

{{ now }}

 

Which should return something like this.

2023-05-24 12:57:45.125776

 

now.year can be used to return the current year.

{{ now.year }}

 

now.month can be used to return the current month.

{{ now.month }}

 

strftime can be used to format the date and time.

{{ now.strftime('%Y-%m-%d') }}

 

strptime can be used to create a date time object using a literal date time string.

{{ now.strptime('2022-11-23', '%Y-%m-%d').strftime('%m/%d/%Y') }}

 

Sometimes, strftime and strptime can used inline to convert literal date time string into a date time object and to then format the date.

{{ now.strptime('2022-11-23', '%Y-%m-%d').strftime('%m/%d/%Y') }}

 

And if you are looping through a list, such as looping through a list of rows in a database, you could do something like this. The tilde is used to convert the int object into a string.

{% for row in results%}
{% set datetime_object = now.strptime("" ~ row['date_updated'] ~ "", "%Y-%m-%d %H:%M:%S").strftime("%m/%d/%Y") %}
{% endfor %}

 

Following are commonly used options.

Option Description Example
%Y Year 2018
%y Year 18
%m Month 01
%b Month Jan
%B Month January
%d Day (with leading zero) 04
%-d Day (without leading zero) 4
%H Hour (24 hour format) 22
%I Hour (12 hour format) 10
%M Minute 56
%S Second 23
%s Microseconds 1677062390
%f Microseconds 508159
%p AM or PM AM
%P am or pm pm

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter e276b6 in the box below so that we can be sure you are a human.