简体   繁体   中英

Converting Int values into padded hours in Python with datetime

Let's say you have an object containing a schedule with start, break, lunch finish hours/minutes stored as integers:

schedules = {
        "employees": {
            "1":{
                "2018":{
                    8:{
                        1: {"day":1, "start_hours": 8, "start_minutes": 0, "1break_start_hours": 9, "1break_start_minutes": 30, "1break_end_hours": 9, "1break_end_minutes": 45, "lunch_start_hours": 11, "lunch_start_minutes": 30, "lunch_end_hours": 10, "lunch_end_minutes": 0, "2break_start_hours": 14, "2break_start_minutes": 0, "2break_end_hours": 14, "2break_end_minutes": 15, "finish_hours": 16, "finish_minutes": 30 }

Is there a way to render the hours/minutes as padded numbers (08 instead of 8 etc) on a page with jinja2 using the datetime module?

In other words, is there a bif or module that allows to convert an integer into padded number?

This doesn't look like you're using datetime at all? But rendering padded numbers is very easy. There's two ways to do that Jinja (and in fact in Python in general):

The "old" style, with a % format string: {{ "%02d:%02d" | format(start_hours, start_minutes) }} {{ "%02d:%02d" | format(start_hours, start_minutes) }}

And the "new" style, using a .format() method: {{ "{:02d}:{:02d}".format(start_hours, start_minutes) }}

See https://pyformat.info/ for more about string formatting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM