Page 1 of 1

Modify Sunrise/Sunset values to shortened format

PostPosted: Tue May 30, 2023 10:14 am
by sumocomputers
I am using a Python script to grab the next Sunset and Sunrise times from Indigo server to display on a custom page.

The value returned is in a long, 24 hour format like 2023-05-30 19:48:44

Trying to figure out how to modify that to a shortened, 12 hour format, that also strips the leading 0 if present, as well as seconds and write it to a variable.

So 2023-05-30 19:48:44 would become 7:48

Here is my current script:

Code: Select all
sunset = indigo.server.calculateSunset() #Indigo Sunset
indigo.variable.updateValue(489151405, format(sunset)) #Sunset into Variable


Any help would be appreciated.

Re: Modify Sunrise/Sunset values to shortened format

PostPosted: Tue May 30, 2023 10:48 am
by DaveL17
You should perhaps familiarize yourself with the Python datetime library which has all the tools you need to make the conversion.

Code: Select all
import datetime
sunset = indigo.server.calculateSunset()  # <-- this yields a datetime object
new_sunset = datetime.datetime.strftime(sunset, "%I:%M")  # <-- this converts the datetime object to a formatted string
indigo.variable.updateValue(489151405, new_sunset) # <-- all Indigo variables are strings

Information on the datetime library and format specifiers can be found here:
https://docs.python.org/3.10/library/datetime.html

Re: Modify Sunrise/Sunset values to shortened format

PostPosted: Tue May 30, 2023 12:14 pm
by sumocomputers
I appreciate the code, and I am definitely reading through that Python datetime library reference page. It is definitely a cure for insomnia!

I made a small modification to strip the leading zero from the hour, and oddly enough I did not find this tip on the official reference, but some other website. Just inserting a hyphen between the percent and letter did the trick. so %I%M becomes %-I%M

Code: Select all
import datetime
sunset = indigo.server.calculateSunset()  # <-- this yields a datetime object
new_sunset = datetime.datetime.strftime(sunset, "%-I:%M")  # <-- this converts the datetime object to a formatted string, hyphen removes leading zero
indigo.variable.updateValue(489151405, new_sunset) # <-- all Indigo variables are strings

Re: Modify Sunrise/Sunset values to shortened format

PostPosted: Tue May 30, 2023 12:25 pm
by DaveL17
Yeah, the Python docs are definitely not the way to learn Python.

After several false starts, I found two sources exceedingly helpful when I was starting out. If you're inclined,

https://www.youtube.com/watch?v=nykOeWgQcHM&list=PLUl4u3cNGP63WbdFxL8giv4yhgdMGaZNA
https://youtube.com/playlist?list=PLTZYG7bZ1u6pqki1CRuW4D4XwsBrRbUpg

The leading hyphen is a great tip.