(Solved) Display Time with AM/PM

Discuss how to use the Ren'Py engine to create visual novels and story-based games. New releases are announced in this section.
Forum rules
This is the right place for Ren'Py help. Please ask one question per thread, use a descriptive subject like 'NotFound error in option.rpy' , and include all the relevant information - especially any relevant code and traceback messages. Use the code tag to format scripts.
Post Reply
Message
Author
User avatar
Nice_Smile
Newbie
Posts: 9
Joined: Wed Jun 05, 2019 2:00 pm
Location: Canada
Contact:

(Solved) Display Time with AM/PM

#1 Post by Nice_Smile » Sat Jun 22, 2019 2:29 pm

** New edit ** If looking for the final revised code, it is located lower on post #5 ***


*** Original post start here ***
I was following the code from the Cookbook post: Scarily simple game calendar... with day parts and it works perfectly with a few custom changes for my needs. I created a "calendar.rpy" file to contain the code.

Code: Select all

# calendar.rpy
init python:

    import datetime

    class GameTime(object):

        def __init__(self, dt="Saturday, April 29 2017"):
            self._dt = datetime.datetime.strptime( dt, "%A, %B %d %Y" )

        def alter(self, **kwargs):
            self._dt += datetime.timedelta( **kwargs )

        def __repr__(self):
            return _strftime("%I:%M %p   %A, %B %d,"" %Y", self._dt.timetuple())

        @property
        def daymark(self):
            return [ k[-1] for k in (
                (0, "Midnight"),
                (1,2,3,4,5, "Very Early Morning"),
                (6,7, "Early Morning"),
                (8,9, "Morning"),
                (10,11, "Mid-Morning"),
                (12, "Noon"),
                (13,14,15, "Afternoon"),
                (16,17, "Mid-Afternoon"),
                (18,19, "Evening"),
                (20,21, "Night"),
                (22,23, "Late Night") ) if self._dt.hour in k ][0]

default gt = GameTime("Saturday, April 29 2017")
I do know how to advance the time needed by using the code in my story script:

Code: Select all

 $ gts.alter( hours = 6,  minutes = 0 ) # Set for 6 AM of started day in code
To display the "Time of Day" by using:

Code: Select all

"[gt.daymark]"  # Shows up on screen: Early Morning
Or the complete time with:

Code: Select all

"[gt]" # Shows up on screen: 6:00 AM Saturday, April 29 2017
But cannot figure out how to only display the "Hours:Minutes AM or PM" on its' own like this:

6:00 AM

And to have just the date displayed:

Saturday, April 29 2017

I need the output "[gt.daymark]" and "[gt]" formats at different times in the story script but would like to be able to have the last 2 mentioned with it also if it's possible.
I have looked, googled and tried numerous Python codes with no luck since I am a novice. I guess their answers do not play nice with the code that "Remix" posted.
I hope that someone could be kind enough to show me the way if possible?

Thank you for your time!
Last edited by Nice_Smile on Sat Jun 29, 2019 12:59 pm, edited 3 times in total.
Currently using Ren'Py v.7.2.2.491

drKlauz
Regular
Posts: 168
Joined: Mon Oct 12, 2015 3:04 pm
Contact:

Re: Looking to display Time with AM/PM

#2 Post by drKlauz » Sat Jun 22, 2019 4:29 pm

Try adding these to class

Code: Select all

        @property
        def time_str(self):
            return _strftime("%I:%M %p",self._dt.timetuple())
        @property
        def date_str(self):
            return _strftime("%A, %B %d %Y",self._dt.timetuple())
Use

Code: Select all

"[gt.time_str] - [gt.date_str]"

User avatar
Nice_Smile
Newbie
Posts: 9
Joined: Wed Jun 05, 2019 2:00 pm
Location: Canada
Contact:

Re: Looking to display Time with AM/PM

#3 Post by Nice_Smile » Sat Jun 22, 2019 5:11 pm

Thank you so much drKlauz!

It works perfectly. I tried something that was kinda close to that code but it kept throwing up errors compared to yours.

Too bad this forum does not have a "kudos" feature to thank you.

So all I can say again is thank you so much!
Currently using Ren'Py v.7.2.2.491

drKlauz
Regular
Posts: 168
Joined: Mon Oct 12, 2015 3:04 pm
Contact:

Re: (Solved) Display Time with AM/PM

#4 Post by drKlauz » Sat Jun 22, 2019 6:40 pm

Come to think about it, it may be better to manually construct time/date strings, as python uses player's machine locale, so if some german or russian guy play your game, it may return something you not expecting, many fonts don't support glyphs for these languages, also layout may become visually broken.
Just replace code inside time_str/date_str to something similar to daymark.

Anyway, good luck with you game :D

User avatar
Nice_Smile
Newbie
Posts: 9
Joined: Wed Jun 05, 2019 2:00 pm
Location: Canada
Contact:

Re: (Solved) Display Time with AM/PM

#5 Post by Nice_Smile » Tue Jun 25, 2019 8:22 pm

drKlauz wrote:
Sat Jun 22, 2019 6:40 pm
Come to think about it, it may be better to manually construct time/date strings, as python uses player's machine locale, so if some german or russian guy play your game, it may return something you not expecting, many fonts don't support glyphs for these languages, also layout may become visually broken.
Just replace code inside time_str/date_str to something similar to daymark.

Anyway, good luck with you game :D
Oh! With everything on the go.... I never thought of that until you mentioned it. I was reading a post found on stackoverflow.com site in regards of locale.

Taken from that site: START of copied text ----
Link -> to page on stackoverflow.com (about halfway down the page)
Python's strftime() is only guaranteed to support the format codes from C89 (see the list).

Useful additional format codes are defined by other standards (see the Linux man page for strftime()). For this question, the relevant additional codes are:

%l — The hour (12-hour clock) as a decimal number (range 1 to 12).
%P — Like %p but in lowercase: "am" or "pm" or a corresponding string for the current locale.

I like to use a wrapper function around strftime() to implement additional codes:

Code: Select all

def extendedStrftime(dt, format):

    day  = dt.strftime('%d').lstrip('0')
    hour = dt.strftime('%I').lstrip('0')
    ampm = dt.strftime('%p').lower()

    format = format.replace('%e', day)
    format = format.replace('%l', hour)
    format = format.replace('%P', ampm)

    return dt.strftime(format)
To get an output in the format "2:35pm":

extendedStrftime(dt, '%l:%M%P')

It's also very common to want to format the day without the leading zero, which can be done with the additional code %e:

extendedStrftime(dt, '%e %b %Y') # "1 Jan 2015"

--- END of copied text

Would this be something that would be acceptable in Ren'Py to make it compatible with other locales? The information that I'm finding is getting me confused in regards of different locales.

So much smoke coming out of my ears! I have been also trying to figure if I can use a IF Statement with the output of [gts.daymark] for an event. Meaning that it the gametime calculation is at 8:00AM then show an image.

I guess that it's only me that can take a post of "Scarily simple game calendar... with day parts" and make it "Scarily Complicated" lol

Just in case someone else is looking into this, here is the REVISED code that I have so far:

Code: Select all

### Calendar System
init python:

    import datetime

    class GameTime(object):

        def __init__(self, dt="Saturday April 29 2017"):
            self._dt = datetime.datetime.strptime( dt, "%A %B %d, %Y" )

        def alter(self, **kwargs):
            self._dt += datetime.timedelta( **kwargs )

        def __repr__(self):
            return _strftime("%I:%M %p   %A %B %d,"" %Y", self._dt.timetuple())

        @property ### [gts.daymark] Displays "Time Of Day" according to hour
        def daymark(self):
            return [ k[-1] for k in (
                (0, "Midnight"),
                (1,2,3,4,5, "Very Early Morning"),
                (6,7, "Early Morning"),
                (8,9, "Morning"),
                (10,11, "Mid-Morning"),
                (12, "Noon"),
                (13,14,15, "Afternoon"),
                (16,17, "Late Afternoon"),
                (18,19, "Evening"),
                (20,21, "Night"),
                (22,23, "Late Night") ) if self._dt.hour in k ][0]


### "[gts.time_str]" Displays "Hours:Minutes AM OR PM"
        @property 
        def time_str(self):
            return _strftime("%I:%M %p",self._dt.timetuple())


### "[gts.date_str]" Displays "Weekday, Month DayNumber, Year"
        @property 
        def date_str(self):
            return _strftime("%A, %B %d, %Y",self._dt.timetuple())


### "[gts.date2_str]" Displays "Weekday, Month DayNumber"
        @property 
        def date2_str(self):
            return _strftime("%A, %B %d",self._dt.timetuple())


### "[gts]" Displays "Hours:Minutes AM OR PM Weekday, Month DayNumber, Year"
default gts = GameTime("Saturday April 29 2017") 


# If you want to create an IF Statement event by using Time "hours"
# if gts._dt.hour==18:
# jump process_evening

# Super Thanks to drKlauz for the help!
Last edited by Nice_Smile on Sat Jun 29, 2019 1:03 pm, edited 5 times in total.
Currently using Ren'Py v.7.2.2.491

User avatar
Nice_Smile
Newbie
Posts: 9
Joined: Wed Jun 05, 2019 2:00 pm
Location: Canada
Contact:

Re: (Almost Solved) Display Time with AM/PM

#6 Post by Nice_Smile » Tue Jun 25, 2019 8:32 pm

Opps meant to add the revised code into my last post! Sorry!
Currently using Ren'Py v.7.2.2.491

drKlauz
Regular
Posts: 168
Joined: Mon Oct 12, 2015 3:04 pm
Contact:

Re: (Almost Solved) Display Time with AM/PM

#7 Post by drKlauz » Wed Jun 26, 2019 7:12 am

I meant manually converting date/time to str, but i checked RenPy's _strftime, it automatically support days of week and month names translation. Tho i didn't found AM/PM support, but i guess it is not big deal.
You can either check how _strftime done it work, it is located in
<renpy sdk path>renpy\common\00action_file.rpy
Or you can ignore AM/am being shown bit different.

User avatar
Nice_Smile
Newbie
Posts: 9
Joined: Wed Jun 05, 2019 2:00 pm
Location: Canada
Contact:

Re: (Almost Solved) Display Time with AM/PM

#8 Post by Nice_Smile » Wed Jun 26, 2019 7:43 pm

Before I forget... I greatly appreciate all your information input drKlauz! It makes me learn so much about Python and makes it enjoyable.

From what I've found when using the %p and the locale is en_US then it shows up "AM" or "PM" and in different locale as de_DE then it shows up "am" or "pm" automatically. Source link -> 8.1.7. strftime() and strptime() Behavior

Since you checked RenPy's _strftime, that it automatically support the days of week and month names for translation. Then having "AM" or "am" should not be any issues?

I know that the way of the calendar is written is different formats in the world locales. But I will never display the abbreviated dates. I can understand that displaying the date as "Saturday, April 29, 2017" would be preferred to the locales as "Saturday, 29 April, 2017" but it shouldn't be a deal breaker for a game in my belief. Same as the hours system of "24-hours" or "12-hours".

So with what I currently have, do you think that it would be ok as is?
Currently using Ren'Py v.7.2.2.491

drKlauz
Regular
Posts: 168
Joined: Mon Oct 12, 2015 3:04 pm
Contact:

Re: (Almost Solved) Display Time with AM/PM

#9 Post by drKlauz » Thu Jun 27, 2019 4:40 am

April 29 vs 29 April is formatted by you, when you specify %B %d order in format string, so it will stay stable.
AM/am is not big deal.
So, yep, should be fine i believe.
Good luck with your game. Glad if helped :D

User avatar
Nice_Smile
Newbie
Posts: 9
Joined: Wed Jun 05, 2019 2:00 pm
Location: Canada
Contact:

Re: (Almost Solved) Display Time with AM/PM

#10 Post by Nice_Smile » Fri Jun 28, 2019 8:05 am

Again, so many thanks for helping me out!

Instead of creating a new question thread since it pertains to the same Time codes...

I have been trying to figure out if I can create an IF Statement from the [gts.daymark] or [gts.time_str] (since it's almost the same) for an event. Meaning that IF the gametime is at 8:00AM THEN show an image or jump to a label (something like that). I cannot seem to find the proper way going with the existing code that I have already here with Ren'Py.

Would it be possible to create an IF Statement with [gts.daymark] or [gts.time_str] output?
Currently using Ren'Py v.7.2.2.491

drKlauz
Regular
Posts: 168
Joined: Mon Oct 12, 2015 3:04 pm
Contact:

Re: (Almost Solved) Display Time with AM/PM

#11 Post by drKlauz » Fri Jun 28, 2019 8:15 am

Better use numerical hour, as daymark/timestr are decorative functions and may/will change, for example if you add translation.
If you want simple checks:

Code: Select all

if gts._dt.hour==18:
  jump process_evening
But if you want more complex date/time system with planned events etc then you probably should rework whole thing to better fit your needs.

User avatar
Nice_Smile
Newbie
Posts: 9
Joined: Wed Jun 05, 2019 2:00 pm
Location: Canada
Contact:

Re: (Almost Solved) Display Time with AM/PM

#12 Post by Nice_Smile » Sat Jun 29, 2019 12:54 pm

Actually the code you gave me is more than perfect for my needs! I updated my post #5 (Revised Code) with all the codes in case it will help others.

Thank you ever so much drKlauz for your much appreciated help!
Currently using Ren'Py v.7.2.2.491

Post Reply

Who is online

Users browsing this forum: Ayael, Google [Bot]