Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Sunrise and Sunset from terminal

275 views
Skip to first unread message

sl...@gmx.com

unread,
Sep 23, 2023, 6:00:05 PM9/23/23
to
Is there a way to get sunrise and sunset time from command interpreter?
I want to use its output for a script!

ghe2001

unread,
Sep 23, 2023, 6:00:05 PM9/23/23
to
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256


------- Original Message -------
On Saturday, September 23rd, 2023 at 3:51 PM, sl...@gmx.com <sl...@gmx.com> wrote:


> Is there a way to get sunrise and sunset time from command interpreter?

Looks like several:

https://duckduckgo.com/?t=ftsa&q=linux+sunrise&ia=web

--
Glenn English
-----BEGIN PGP SIGNATURE-----
Version: ProtonMail

wsBzBAEBCAAnBYJlD19ECZCf14YxgqyMMhYhBCyicw9CUnAlY0ANl5/XhjGC
rIwyAABG0QgAynKIW/hSAR3yMZSdQYTjlK1tvjSHlml7tmKhTLN2CfUe2/Bv
1dhvuV4VG85UeVpDHzh59hXkbJM6PPmk366sTFM0kvUhESU/uJzcHPIPbA4r
e87vFIj9helcL9ExR5m7JYxgCBW+sg5Uzv3/hzoaUTWWpHDAzRhjWL08odel
IZv9iUYsCwZJV3ka4vsaiBUcy1yazyUMEK0sZgmGf+51Ob5hhO4EMobGDfj4
ingcbqGVbtdbQlctqauikSGU+cYVUPjZOjdaiNyvIT9oV/U9G51aMs8jjydv
F7JUnUWV1Nsi8sluJETxy1qbLC2hvE8ja4UzSVFU9GF/Eox1uMLcYw==
=c/IX
-----END PGP SIGNATURE-----

piorunz

unread,
Sep 23, 2023, 6:40:06 PM9/23/23
to
On 23/09/2023 22:51, sl...@gmx.com wrote:
> Is there a way to get sunrise and sunset time from command interpreter?
> I want to use its output for a script!

Of course.

#!/bin/bash

SunTimes=$(curl --silent "https://www.timeanddate.com/sun/uk/london"
2>/dev/null)

SunriseTime=$(echo "$SunTimes" | grep -o 'Sunrise Today.*' | awk '{print
$3}' | sed 's/[^0-9]//g')
SunsetTime=$(echo "$SunTimes" | grep -o 'Sunset Today.*' | awk '{print
$3}' | sed 's/[^0-9]//g')

# Optional: Insert a colon between hours and minutes
SunriseTime="${SunriseTime:0:2}:${SunriseTime:2}"
SunsetTime="${SunsetTime:0:2}:${SunsetTime:2}"

echo "Sunrise Today:" $SunriseTime
echo "Sunset Today:" $SunsetTime

--
With kindest regards, Piotr.

⢀⣴⠾⠻⢶⣦⠀
⣾⠁⢠⠒⠀⣿⡁ Debian - The universal operating system
⢿⡄⠘⠷⠚⠋⠀ https://www.debian.org/
⠈⠳⣄⠀⠀⠀⠀

Felix Miata

unread,
Sep 23, 2023, 6:50:06 PM9/23/23
to
piorunz composed on 2023-09-23 23:35 (UTC+0100):

> #!/bin/bash

> SunTimes=$(curl --silent "https://www.timeanddate.com/sun/uk/london"
> 2>/dev/null)

> SunriseTime=$(echo "$SunTimes" | grep -o 'Sunrise Today.*' | awk '{print
> $3}' | sed 's/[^0-9]//g')
> SunsetTime=$(echo "$SunTimes" | grep -o 'Sunset Today.*' | awk '{print
> $3}' | sed 's/[^0-9]//g')

> # Optional: Insert a colon between hours and minutes
> SunriseTime="${SunriseTime:0:2}:${SunriseTime:2}"
> SunsetTime="${SunsetTime:0:2}:${SunsetTime:2}"

> echo "Sunrise Today:" $SunriseTime
> echo "Sunset Today:" $SunsetTime

> sh srss.sh
Sunrise Today: 64:7889657242711361093201601361071834
Sunset Today: 65:7242711361093201601361071834
>

That sort of resembles the half day format common outside the military.
--
Evolution as taught in public schools is, like religion,
based on faith, not based on science.

Team OS/2 ** Reg. Linux User #211409 ** a11y rocks!

Felix Miata

piorunz

unread,
Sep 23, 2023, 7:00:06 PM9/23/23
to
On 23/09/2023 23:45, Felix Miata wrote:

>> sh srss.sh
> Sunrise Today: 64:7889657242711361093201601361071834
> Sunset Today: 65:7242711361093201601361071834
>>
>
> That sort of resembles the half day format common outside the military.

Sorry, works for me.

./suntimes.sh
Sunrise Today: 06:47
Sunset Today: 18:57

Don't forget to fix line breaks in three lines (curl and grep/awk/sed
lines), because e-mail client splitted them.
Also, your city may not be supported by this website, this you changed it?

Greg Wooledge

unread,
Sep 23, 2023, 7:10:06 PM9/23/23
to
On Sat, Sep 23, 2023 at 06:45:08PM -0400, Felix Miata wrote:
> piorunz composed on 2023-09-23 23:35 (UTC+0100):
>
> > SunTimes=$(curl --silent "https://www.timeanddate.com/sun/uk/london"
> > 2>/dev/null)
[...]

> > sh srss.sh
> Sunrise Today: 64:7889657242711361093201601361071834
> Sunset Today: 65:7242711361093201601361071834
> >
>
> That sort of resembles the half day format common outside the military.

The web site in question <https://www.timeanddate.com/sun/uk/london>
gives me a page full of HTML and Javascript and gods only know what
else. The shell script which "parses" this is absolutely not doing
it correctly, if indeed it's even *possible* to do correctly.

Take it apart piece by piece.

unicorn:~$ curl -s https://www.timeanddate.com/sun/uk/london | grep 'Sunrise Today'
</script></section></header><main class="tpl-banner__main layout-grid layout-grid--sky tpl-banner__main--astro"><section class="layout-grid__hero tpl-banner__hero"><nav class=nav-3><div class=fixed><a href="/astronomy/uk/london">Sun & Moon Today </a><a href="/sun/uk/london" class=active>Sunrise & Sunset </a><a href="/moon/uk/london">Moonrise & Moonset </a><a href="/moon/phases/uk/london">Moon Phases </a><a href="/eclipse/in/uk/london">Eclipses </a><a href="/astronomy/night/uk/london">Night Sky </a></div></nav></section><article class="layout-grid__main tpl-banner__content"><section class=bk-focus><div id=qlook class=bk-focus__qlook><img src="//c.tadst.com/gfx/n/i/sun.png" width=120 height=120><div class="h1 dn-mob">Daylight</div><p class=dn-mob>6:47 am &#8211; 6:57 pm<br>12 hours, 10 minutes</p></div><div class=bk-focus__info><table class="table table--left table--inner-borders-rows"><tbody><tr><th>Current Time: </th><td id=smct>Sep 23, 2023 at 11:51:30 pm</td></tr><tr><th>Sun Direction: </th><td id=sunaz><span class="comp sa30" title="Map direction North">↑</span> 341° North</td></tr><tr><th>Sun Altitude: </th><td id=sunalt>-37.1°</td></tr><tr><th>Sun Distance: </th><td id=sundist>93.273 million mi</td></tr><tr><th>Next Solstice: </th><td><a href="/calendar/seasons.html?n=136" title="Click to see detailed season information for London">Dec 22, 2023 3:27 am (Winter)</a></td></tr><tr><th>Sunrise Today: </th><td>6:47 am<span class="comp sa8" title="Map direction East">↑</span> 89° East</td></tr><tr><th>Sunset Today: </th><td>6:57 pm<span class="comp sa24" title="Map direction West">↑</span> 271° West</td></tr></tbody></table></div><div id=bk-map class=bk-focus__map><a href="/time/map/#!cities=136"><img title="Map showing the location of London. Click map to see the location on our worldwide Time Zone Map." src="//c.tadst.com/gfx/citymap/uk-10.png?9" alt="Location of London" width=320 height=160><img id=map-mrk src="//c.tadst.com/gfx/n/icon/icon-map-pin.png" class=fadeInDown style="left:136px;top:107px;position:absolute" alt=Location title="Location of London" width=18 height=34></a></div></section><div class=fixed></div>

As you can see, parsing the 2100-character-long "line" of the page which
contains the substring "Sunrise Today" gives more rubbish than answer.
Simply discarding all of the non-digit characters leaves you with all
of the digit characters from the rubbish, which is not by any means a
useful piece of output.

So, what to do instead? I would first look for a data source that's
not intended to be displayed by a Javascript-enabled web browser.
Something that gives you the results in plain text would be great.
I doubt such a thing can be found easily. Something that gives the
results in, say, JSON or XML format might be easier to find. Then
you "only" need to write code that parses JSON or XML (realistically
meaning you call upon a dedicated tool or library for doing so).

Failing that -- and really, this is a LAST resort, not a first resort --
you could parse the HTML here. Find a tool that parses HTML, which
usually have names like "xpath" or "xslt" or something. Then analyze
the HTML yourself, figure out the hierarchical structure of the elements,
and use your knowledge of this layout when applying your HTML parsing
tool.

In this specific example, I see a table with

<tr><th>Sunrise Today: </th><td>6:47 am

inside it. A decent HTML parsing tool should be able to zero in on
the correct table, then iterate through rows until it finds the one
with "Sunrise Today" as a substring in its <th> element, and then
spit out the first <td> element.

Finding an alternative data source that doesn't require this level of
parsing is a far superior choice, if it's possible.

By the way, do you know what tool does NOT parse HTML correctly?
A mashup of grep, awk and sed. Seriously, don't do this, ever.

Felix Miata

unread,
Sep 23, 2023, 7:30:06 PM9/23/23
to
piorunz composed on 2023-09-23 23:50 (UTC+0100):

> Felix Miata wrote:

>>> sh srss.sh
>> Sunrise Today: 64:7889657242711361093201601361071834
>> Sunset Today: 65:7242711361093201601361071834
>

>> That sort of resembles the half day format common outside the military.

> Sorry, works for me.

> Don't forget to fix line breaks in three lines (curl and grep/awk/sed
> lines), because e-mail client splitted them.
> Also, your city may not be supported by this website, this you changed it?

Still doesn't make sense:

> cat srss.sh
#!/bin/bash

SunTimes=$(curl --silent "https://www.timeanddate.com/sun/usa/gainesville" 2>/dev/null)

SunriseTime=$(echo "$SunTimes" | grep -o 'Sunrise Today.*' | awk '{print $3}' | sed 's/[^0-9]//g')
SunsetTime=$(echo "$SunTimes" | grep -o 'Sunset Today.*' | awk '{print $3}' | sed 's/[^0-9]//g')

# Optional: Insert a colon between hours and minutes
SunriseTime="${SunriseTime:0:2}:${SunriseTime:2}"
SunsetTime="${SunsetTime:0:2}:${SunsetTime:2}"

echo "Sunrise Today:" $SunriseTime
echo "Sunset Today:" $SunsetTime
> sh srss.sh
Sunrise Today: 71:8
Sunset Today: 72:4
>
It's still that idiotic AM/PM nonsense, and the : is in the wrong place.

piorunz

unread,
Sep 23, 2023, 7:40:06 PM9/23/23
to
On 24/09/2023 00:22, Felix Miata wrote:

>> sh srss.sh
> Sunrise Today: 71:8
> Sunset Today: 72:4
>>
> It's still that idiotic AM/PM nonsense, and the : is in the wrong place.

Your city in my terminal is displayed correctly:
Sunrise Today: 07:18
Sunset Today: 19:24

Looks like the website has decided to display it differently for you,
based on your location. For me, it displays in 24 hours format, for you,
in AM/PM format.
You will have to modify the script, but it should be very easy, start
from disabling insert colon section and work from there.

piorunz

unread,
Sep 23, 2023, 7:50:05 PM9/23/23
to
On 24/09/2023 00:04, Greg Wooledge wrote:
> By the way, do you know what tool does NOT parse HTML correctly?
> A mashup of grep, awk and sed. Seriously, don't do this, ever.

I don't care, it works for me perfectly well. My own city, and every
other I tried.

Random city:
$ head -n 3 suntimes.sh | tail -n 1 && ./suntimes.sh
SunTimes=$(curl --silent
"https://www.timeanddate.com/sun/germany/berlin" 2>/dev/null)
Sunrise Today: 06:55
Sunset Today: 19:01

$ head -n 3 suntimes.sh | tail -n 1 && ./suntimes.sh
SunTimes=$(curl --silent
"https://www.timeanddate.com/sun/australia/sydney" 2>/dev/null)
Sunrise Today: 05:42
Sunset Today: 17:52

Enough for my Raspberry Pi controlled garden lights to turn on at dusk
and turn off at dawn. And it's been like that for last 2 years without a
single fail.

You want any better? Write it yourself.

Andy Smith

unread,
Sep 23, 2023, 8:40:07 PM9/23/23
to
Hello,

On Sat, Sep 23, 2023 at 07:04:17PM -0400, Greg Wooledge wrote:
> So, what to do instead? I would first look for a data source that's
> not intended to be displayed by a Javascript-enabled web browser.
> Something that gives you the results in plain text would be great.
> I doubt such a thing can be found easily. Something that gives the
> results in, say, JSON or XML format might be easier to find.

Here's one:

$ curl -s 'https://api.sunrise-sunset.org/json?lat=51.509865&lng=-0.118092&formatted=0' | jq .
{
"results": {
"sunrise": "2023-09-24T05:47:54+00:00",
"sunset": "2023-09-24T17:57:14+00:00",
"solar_noon": "2023-09-24T11:52:34+00:00",
"day_length": 43760,
"civil_twilight_begin": "2023-09-24T05:16:19+00:00",
"civil_twilight_end": "2023-09-24T18:28:49+00:00",
"nautical_twilight_begin": "2023-09-24T04:37:02+00:00",
"nautical_twilight_end": "2023-09-24T19:08:06+00:00",
"astronomical_twilight_begin": "2023-09-24T03:56:14+00:00",
"astronomical_twilight_end": "2023-09-24T19:48:54+00:00"
},
"status": "OK"
}

The documentation is here:

https://sunrise-sunset.org/api

Cheers,
Andy

--
https://bitfolk.com/ -- No-nonsense VPS hosting

piorunz

unread,
Sep 23, 2023, 9:00:06 PM9/23/23
to
Nice, thanks!
Creating a script based on that was a breeze. Not that I needed it :)

Nate Bargmann

unread,
Sep 23, 2023, 11:00:05 PM9/23/23
to
If you don't want to scrape a Web page, or want this information when a
network is not available, the hdate package will do (referenced from:
https://unix.stackexchange.com/a/527031).

Here is an example for Topeka, KS:

$ hdate -l N39.034722 -L W95.695556 -s -z -5
Saturday, 23 September 2023, eve of 9 Tishrei 5784
sunrise: 07:10
sunset: 19:18
hdate: ALERT: The information displayed is for today's Hebrew date.
Because it is now after sunset, that means the data is
for the Gregorian day beginning at midnight.

- Nate

--
"The optimist proclaims that we live in the best of all
possible worlds. The pessimist fears this is true."
Web: https://www.n0nb.us
Projects: https://github.com/N0NB
GPG fingerprint: 82D6 4F6B 0E67 CD41 F689 BBA6 FB2C 5130 D55A 8819

signature.asc

Charles Curley

unread,
Sep 23, 2023, 11:00:05 PM9/23/23
to
On Sat, 23 Sep 2023 19:22:52 -0400
Felix Miata <mrm...@earthlink.net> wrote:

> It's still that idiotic AM/PM nonsense, and the : is in the wrong
> place.

Yup. I think it's locale-dependent, as you surmised.


# Optional: Insert a colon between hours and minutes. AM/PM times
# assumed.
SunriseTime="${SunriseTime:0:1}:${SunriseTime:1}"
SunsetTime="${SunsetTime:0:1}:${SunsetTime:1}"

echo "Sunrise Today:" "$SunriseTime" AM
echo "Sunset Today:" "$SunsetTime" PM

But I concur with Mr. Wooledge, this is hardly ideal.

--
Does anybody read signatures any more?

https://charlescurley.com
https://charlescurley.com/blog/

Greg Wooledge

unread,
Sep 23, 2023, 11:10:06 PM9/23/23
to
On Sun, Sep 24, 2023 at 12:35:18AM +0000, Andy Smith wrote:
> $ curl -s 'https://api.sunrise-sunset.org/json?lat=51.509865&lng=-0.118092&formatted=0' | jq .
> {
> "results": {
> "sunrise": "2023-09-24T05:47:54+00:00",
> "sunset": "2023-09-24T17:57:14+00:00",
> "solar_noon": "2023-09-24T11:52:34+00:00",
> "day_length": 43760,
> "civil_twilight_begin": "2023-09-24T05:16:19+00:00",
> "civil_twilight_end": "2023-09-24T18:28:49+00:00",
> "nautical_twilight_begin": "2023-09-24T04:37:02+00:00",
> "nautical_twilight_end": "2023-09-24T19:08:06+00:00",
> "astronomical_twilight_begin": "2023-09-24T03:56:14+00:00",
> "astronomical_twilight_end": "2023-09-24T19:48:54+00:00"
> },
> "status": "OK"
> }
>
> The documentation is here:
>
> https://sunrise-sunset.org/api

Yes, that's pretty reasonable. The times are given in UTC, so they
must be converted. Fortunately, GNU date can do that for us.

As a one-liner:

unicorn:~$ curl -s 'https://api.sunrise-sunset.org/json?lat=41.4483&lng=-82.1689&formatted=0' | jq -r .results.sunrise,.results.sunset | { read -r sunrise; read -r sunset; date "+Sunrise: %R" -d "$sunrise"; date "+Sunset: %R" -d "$sunset"; }
Sunrise: 07:16
Sunset: 19:24

As a script:

#!/bin/sh
lat=41.4483
lng=-82.1689
curl -s "https://api.sunrise-sunset.org/json?lat=$lat&lng=$lng&formatted=0" |
jq -r .results.sunrise,.results.sunset | {
read -r sunrise
read -r sunset
date "+Sunrise: %R" -d "$sunrise"
date "+Sunset: %R" -d "$sunset"
}

Stefano

unread,
Sep 24, 2023, 5:30:06 AM9/24/23
to
Cool this site..i didn't know it..thanks....

Tom Browder

unread,
Sep 24, 2023, 4:40:07 PM9/24/23
to
On Sun, Sep 24, 2023 at 00:00 sl...@gmx.com <sl...@gmx.com> wrote:
Is there a way to get sunrise and sunset time from command interpreter?
I want to use its output for a script!

You can calculate it yourself using a Raku module at https://github.com/tbrowder/Astro-Sunrise/;

Search https://raku.land to find any published Raku module.

There are also Perl modules to do the same thing to be found on CPAN.

-Tom

Carles Pina i Estany

unread,
Sep 27, 2023, 6:20:07 AM9/27/23
to

Hi,

sudo apt install python3-ephem

And in one line:

"""
(LATITUDE=51.5; LONGITUDE=0.12; python3 -c "import ephem; o=ephem.Observer(); o.lat, o.lon = $LATITUDE, $LONGITUDE; print('Sunrise:', o.next_rising(ephem.Sun()).datetime(), 'Sunset:', o.next_setting(ephem.Sun()).datetime())")
"""

The output:

Sunrise: 2023-09-28 05:34:38.906872 Sunset: 2023-09-27 17:14:27.209178

It fits in an alias :-)

The () is to avoid leaving LATITUDE and LONGITUDE defined.

I wouldn't use an external service for this, it can be avoided.

On 23 Sep 2023 at 23:51:44, sl...@gmx.com wrote:
> Is there a way to get sunrise and sunset time from command interpreter?
> I want to use its output for a script!
--
Carles Pina i Estany
https://carles.pina.cat || Wiktionary translations: https://kamus.pina.cat

Curt

unread,
Sep 27, 2023, 11:50:06 AM9/27/23
to
On 2023-09-27, Carles Pina i Estany <car...@pina.cat> wrote:
>
> Hi,
>
> sudo apt install python3-ephem
>

I think hdate could also work for this.

Sven Hoexter

unread,
Sep 29, 2023, 10:10:07 AM9/29/23
to
On Wed, Sep 27, 2023 at 11:12:02AM +0100, Carles Pina i Estany wrote:
>
> Hi,
>
> sudo apt install python3-ephem
>
> And in one line:
>
> """
> (LATITUDE=51.5; LONGITUDE=0.12; python3 -c "import ephem; o=ephem.Observer(); o.lat, o.lon = $LATITUDE, $LONGITUDE; print('Sunrise:', o.next_rising(ephem.Sun()).datetime(), 'Sunset:', o.next_setting(ephem.Sun()).datetime())")
> """
>

Some more options for the fun of it:
python3-suntime / https://github.com/SatAgro/suntime

I converted that code into a Lua script [1] to run it
on OpenWrt based systems, in case someone is up for something to
run in more constrained environments.
https://git.sven.stormbind.net/?p=sven/scripts.git;a=blob_plain;f=weblogpro/suntime.lua;hb=HEAD

Cheers,
Sven

Bruno Kleinert

unread,
Sep 29, 2023, 12:50:09 PM9/29/23
to
Am Samstag, dem 23.09.2023 um 23:51 +0200 schrieb sl...@gmx.com:
Is there a way to get sunrise and sunset time from command interpreter?
I want to use its output for a script!


Hi,

in case you're looking for a possibility to execute commands at sunset and/or sunrise, I use remind for this (apt install remind) to trigger my roller blinds. Pro: Does not rely on any external web service.

Kind regards,
Bruno

Karl Vogel

unread,
Sep 29, 2023, 5:40:05 PM9/29/23
to
On Fri, Sep 29, 2023 at 12:48:56PM -0400, Bruno Kleinert wrote:
> Am Samstag, dem 23.09.2023 um 23:51 +0200 schrieb sl...@gmx.com:
> > Is there a way to get sunrise and sunset time from command interpreter?
> > I want to use its output for a script!
>
> in case you're looking for a possibility to execute commands at sunset
> and/or sunrise, I use remind for this (apt install remind) to trigger my
> roller blinds. Pro: Does not rely on any external web service.

Remind is an incredibly useful program. Give it your latitude and longitude,
and it can tell you sunrise and sunset times. My coordinates:

https://www.google.com/search?q=dayton+ohio+latitude+longitude+degrees+minutes+seconds
Dayton, OH, USA is located at GPS coordinates of
39d 45m 32.2164s N and 84d 11m 29.7780s W.

Version of remind:

me% remind -V 2>&1 | grep Copyright
REMIND 04.02.04 (English version) Copyright 1992-2023 Dianne Skoll

Remind script:

me% cat sunrise-sunset.rem
; Show sunrise/sunset
SET $LatDeg 39
SET $LatMin 45
SET $LatSec 32
SET $LongDeg 84
SET $LongMin 11
SET $LongSec 29
MSG sunrise at [sunrise(trigdate())], sunset at [sunset(trigdate())]

Sunrise/sunset for today:

me% remind -h sunrise-sunset.rem '*1' | sed -e '/^$/d'
Reminders for Friday, 29th September, 2023 (today):
sunrise at 07:30, sunset at 19:22

Sunrise/sunset for the next week:

me% remind -h sunrise-sunset.rem '*7' | sed -e '/^$/d'
Reminders for Friday, 29th September, 2023 (today):
sunrise at 07:30, sunset at 19:22
Reminders for Saturday, 30th September, 2023:
sunrise at 07:31, sunset at 19:21
Reminders for Sunday, 1st October, 2023:
sunrise at 07:32, sunset at 19:19
Reminders for Monday, 2nd October, 2023:
sunrise at 07:33, sunset at 19:18
Reminders for Tuesday, 3rd October, 2023:
sunrise at 07:34, sunset at 19:15
Reminders for Wednesday, 4th October, 2023:
sunrise at 07:35, sunset at 19:15
Reminders for Thursday, 5th October, 2023:
sunrise at 07:36, sunset at 19:12

--
Karl Vogel I don't speak for anyone but myself.

German: "Er hat da geparkt, wo ihm die Karre vom Arsch gefallen ist."
English: "He parked where the car fell off his ass."
--Reddit comment about stupid/illegal parking
0 new messages