Formatting Text/Time in Python - BGE

Hey guys,

I’m trying to format text/the time in this specific script, shared by Monster. What I would like to achieve is for numbers below 10 to have a “0” in front of them. So that the time looks like 03:08 instead of 3:8

nTime = datetime.datetime.now()
time_curr = "{}.{}_{}.{}".format(nTime.month, nTime.day, nTime.hour, nTime.minute)
print(time_curr)

My question is - how would one do this the most efficiently? I could possibly throw in a few if statements but isn’t there a way to tell Blender to display time/date with 2 digit numbers?

ALSO:

This is another question, if anyone knows - how to get a portion of a string?

I know how to get specific characters but how would you do - print the last 8 characters of a string and nothing before them?

Thank you in advance guys, much much appreciated,

Pete

Slicing.

“question”[:4] is ques
“question”[2:4] is es
(“0000”+str(3))[-2:] is “03”

Strings can be indexed and sliced like lists:


myString = "abcdefghijk..."
print(mystring[:8])

As for your first question, Im about to leave the house so don’t have time to figure it out. Probably something like:


if nTime.hour < 10:


timeString = "0" + str(nTime.hour)

Then just print/display the constructed string.

Hope this helps!

oups I come too late:

import time


print(time.strftime("%b %d %Y %H:%M:%S", time.gmtime()))


chain = "verylongstring"


print(chain[-8:])

VegetableJuiceF @ NICE! So just needed the [-8:] in the end :slight_smile:

battery @ Yeah I was thinking that aswell with the “if” statement, was just wondering if there was a way to tell blender to format the time differently in the format line…

Anyways, great resources on the slicing, thanks guys! It will be so much easier working with paths now.

Still, If anyone knows about the time formatting thing - please do leave a comment!

[EDIT]

youle @ BIG BIG SHOUT!

Works even better than the way I did it first. Wow this is gonna be awesome, thanks a lot guys

Pete

Try this formatting:


"{:02d}".format(integerValue)

Added to your code:


...
time_curr = "{:02d}.{:02d}_{:02d}.{:02d}".format(nTime.month, nTime.day, nTime.hour, nTime.minute)
...

Sweeet, nice one Monster! Works like a beast now :slight_smile:

Trying to set up a multiple-saves system, it’s coming along nicely.

Thanks guys! I owe you all a beer now…

[SOLVED]

Oh one more thing while this thread is still active, any way to sort a list backwards? So instead of 1 2 3 4 it’ll be 4 3 2 1.

Or, is there a way a for loop can loop through a list, but backwards, starting from the last entry?

This should do the trick:


for i in reversed(myList):
print(i)

Perfect! Thank you very much for all the info