or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# SunTime

1

2

Simple sunset and sunrise time calculation python library. Provides astronomical calculations for determining sunrise and sunset times for any geographic location and date, with support for various timezones and edge case handling for polar regions.

3

4

## Package Information

5

6

- **Package Name**: suntime

7

- **Language**: Python

8

- **Installation**: `pip install suntime`

9

- **License**: LGPLv3

10

- **Version**: 1.3.2

11

12

## Core Imports

13

14

```python

15

from suntime import Sun, SunTimeException

16

```

17

18

## Basic Usage

19

20

```python

21

import datetime

22

from dateutil import tz

23

from suntime import Sun, SunTimeException

24

25

# Create Sun instance with coordinates (Warsaw, Poland)

26

warsaw_lat = 51.21

27

warsaw_lon = 21.01

28

sun = Sun(warsaw_lat, warsaw_lon)

29

30

# Get today's sunrise and sunset in UTC

31

today_sr = sun.get_sunrise_time()

32

today_ss = sun.get_sunset_time()

33

print(f'Today at Warsaw the sun raised at {today_sr.strftime("%H:%M")} and set at {today_ss.strftime("%H:%M")} UTC')

34

35

# Get sunrise and sunset for specific date with timezone

36

specific_date = datetime.date(2024, 10, 3)

37

local_tz = tz.gettz('Europe/Warsaw')

38

abd_sr = sun.get_sunrise_time(specific_date, local_tz)

39

abd_ss = sun.get_sunset_time(specific_date, local_tz)

40

print(f'On {specific_date} the sun raised at {abd_sr.strftime("%H:%M")} and set at {abd_ss.strftime("%H:%M")}')

41

42

# Error handling for polar regions

43

try:

44

north_sun = Sun(87.55, 0.1) # High latitude

45

polar_sunrise = north_sun.get_sunrise_time(specific_date)

46

except SunTimeException as e:

47

print(f"Error: {e}")

48

```

49

50

## Capabilities

51

52

### Sunrise Calculation

53

54

Calculate sunrise time for a given location and date with timezone support.

55

56

```python { .api }

57

def get_sunrise_time(self, at_date=datetime.now(), time_zone=timezone.utc):

58

"""

59

Calculate sunrise time for specified date and timezone.

60

61

Parameters:

62

- at_date: datetime, reference date (defaults to current date)

63

- time_zone: timezone object with tzinfo(), defaults to UTC

64

65

Returns:

66

datetime: Sunrise datetime object

67

68

Raises:

69

SunTimeException: When there is no sunrise on given location and date

70

"""

71

```

72

73

### Sunset Calculation

74

75

Calculate sunset time for a given location and date with timezone support.

76

77

```python { .api }

78

def get_sunset_time(self, at_date=datetime.now(), time_zone=timezone.utc):

79

"""

80

Calculate sunset time for specified date and timezone.

81

82

Parameters:

83

- at_date: datetime, reference date (defaults to current date)

84

- time_zone: timezone object with tzinfo(), defaults to UTC

85

86

Returns:

87

datetime: Sunset datetime object

88

89

Raises:

90

SunTimeException: When there is no sunset on given location and date

91

"""

92

```

93

94

### Low-Level Sun Time Calculation

95

96

Advanced method for calculating sunrise or sunset with custom zenith angle.

97

98

```python { .api }

99

def get_sun_timedelta(self, at_date, time_zone, is_rise_time=True, zenith=90.8):

100

"""

101

Calculate sunrise or sunset timedelta with custom zenith angle.

102

103

Parameters:

104

- at_date: datetime, reference date

105

- time_zone: timezone object with tzinfo()

106

- is_rise_time: bool, True for sunrise, False for sunset (default: True)

107

- zenith: float, sun reference zenith angle in degrees (default: 90.8)

108

109

Returns:

110

timedelta: Time offset for sunrise/sunset, or None if sun doesn't rise/set

111

"""

112

```

113

114

### Deprecated Methods

115

116

Legacy methods maintained for backward compatibility.

117

118

```python { .api }

119

def get_local_sunrise_time(self, at_date=datetime.now(), time_zone=None):

120

"""

121

DEPRECATED: Use get_sunrise_time() with proper timezone instead.

122

123

Parameters:

124

- at_date: datetime, reference date (defaults to current date)

125

- time_zone: timezone object, defaults to None

126

127

Returns:

128

datetime: Sunrise datetime object

129

"""

130

131

def get_local_sunset_time(self, at_date=datetime.now(), time_zone=None):

132

"""

133

DEPRECATED: Use get_sunset_time() with proper timezone instead.

134

135

Parameters:

136

- at_date: datetime, reference date (defaults to current date)

137

- time_zone: timezone object, defaults to None

138

139

Returns:

140

datetime: Sunset datetime object

141

"""

142

```

143

144

## Types

145

146

### Sun Class

147

148

Main class for sunrise and sunset calculations.

149

150

```python { .api }

151

class Sun:

152

"""

153

Approximated calculation of sunrise and sunset datetimes.

154

155

Uses astronomical algorithms to calculate sun times for any geographic location.

156

Handles edge cases for polar regions where sun may not rise or set.

157

"""

158

159

def __init__(self, lat, lon):

160

"""

161

Initialize Sun instance with geographic coordinates.

162

163

Parameters:

164

- lat: float, latitude in decimal degrees (-90 to +90)

165

- lon: float, longitude in decimal degrees (-180 to +180)

166

"""

167

168

# Computed attribute

169

lngHour: float # Longitude converted to hours (lon / 15)

170

```

171

172

### Exception Classes

173

174

```python { .api }

175

class SunTimeException(Exception):

176

"""

177

Exception raised when sunrise/sunset cannot be calculated.

178

179

Typically occurs in polar regions during certain seasons where

180

the sun does not rise or set on specific dates.

181

"""

182

183

def __init__(self, message):

184

"""

185

Initialize exception with error message.

186

187

Parameters:

188

- message: str, descriptive error message

189

"""

190

```

191

192

### Module Constants

193

194

```python { .api }

195

__version__: str # Package version string ('1.3.2')

196

__author__: str # Author name ('Krzysztof Stopa')

197

__license__: str # License type ('LGPLv3')

198

```

199

200

## Usage Examples

201

202

### Working with Different Timezones

203

204

```python

205

import datetime

206

from dateutil import tz

207

from suntime import Sun

208

209

# Create sun instance for New York

210

ny_sun = Sun(40.7128, -74.0060)

211

212

# Get times in different timezones

213

utc_sunrise = ny_sun.get_sunrise_time()

214

local_sunrise = ny_sun.get_sunrise_time(time_zone=tz.gettz('America/New_York'))

215

london_sunrise = ny_sun.get_sunrise_time(time_zone=tz.gettz('Europe/London'))

216

217

print(f"NYC sunrise in UTC: {utc_sunrise}")

218

print(f"NYC sunrise in local time: {local_sunrise}")

219

print(f"NYC sunrise in London time: {london_sunrise}")

220

```

221

222

### Historical and Future Dates

223

224

```python

225

from suntime import Sun

226

import datetime

227

228

sun = Sun(48.8566, 2.3522) # Paris coordinates

229

230

# Historical date

231

historical_date = datetime.date(1969, 7, 20) # Moon landing

232

historical_sunrise = sun.get_sunrise_time(historical_date)

233

234

# Future date

235

future_date = datetime.date(2030, 1, 1)

236

future_sunset = sun.get_sunset_time(future_date)

237

238

print(f"Paris sunrise on Moon landing day: {historical_sunrise}")

239

print(f"Paris sunset on New Year 2030: {future_sunset}")

240

```

241

242

### Error Handling for Extreme Latitudes

243

244

```python

245

from suntime import Sun, SunTimeException

246

import datetime

247

248

# Test polar region during winter

249

arctic_sun = Sun(80.0, 0.0) # High Arctic

250

winter_date = datetime.date(2024, 12, 21) # Winter solstice

251

252

try:

253

sunrise = arctic_sun.get_sunrise_time(winter_date)

254

print(f"Arctic sunrise: {sunrise}")

255

except SunTimeException as e:

256

print(f"No sunrise in Arctic winter: {e}")

257

258

try:

259

sunset = arctic_sun.get_sunset_time(winter_date)

260

print(f"Arctic sunset: {sunset}")

261

except SunTimeException as e:

262

print(f"No sunset in Arctic winter: {e}")

263

```

264

265

### Custom Zenith Calculations

266

267

```python

268

from suntime import Sun

269

import datetime

270

271

sun = Sun(37.7749, -122.4194) # San Francisco

272

date = datetime.date(2024, 6, 21) # Summer solstice

273

274

# Standard zenith (90.8°) - accounts for atmospheric refraction

275

standard_delta = sun.get_sun_timedelta(date, None, is_rise_time=True)

276

277

# Geometric horizon (90°)

278

geometric_delta = sun.get_sun_timedelta(date, None, is_rise_time=True, zenith=90.0)

279

280

# Civil twilight (96°)

281

civil_delta = sun.get_sun_timedelta(date, None, is_rise_time=True, zenith=96.0)

282

283

print(f"Standard sunrise offset: {standard_delta}")

284

print(f"Geometric sunrise offset: {geometric_delta}")

285

print(f"Civil twilight offset: {civil_delta}")

286

```