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.

OptionDescriptionExample
%YYear2018
%yYear18
%mMonth01
%bMonthJan
%BMonthJanuary
%dDay (with leading zero)04
%-dDay (without leading zero)4
%HHour (24 hour format)22
%IHour (12 hour format)10
%MMinute56
%SSecond23
%sMicroseconds1677062390
%fMicroseconds508159
%pAM or PMAM
%Pam or pmpm

 




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 a9b5b8 in the box below so that we can be sure you are a human.