Blame view

src/core/celme/dates.py 36.6 KB
4f8cc5f0   aklotz   Package CelMe Cel...
1
2
3
4
import datetime
import math
import doctest
import typing 
17d8b9ff   aklotz   celme mise à jour.
5
from .durations import Duration
4f8cc5f0   aklotz   Package CelMe Cel...
6
7
8
9
10
11
12
13
14
15

# ========================================================
# ========================================================
# === DATE
# ========================================================
# ========================================================

class Date:
    """ Class to convert dates for astronomy

17d8b9ff   aklotz   celme mise à jour.
16
    *Date formats are:*
4f8cc5f0   aklotz   Package CelMe Cel...
17
    
17d8b9ff   aklotz   celme mise à jour.
18
19
20
21
22
23
24
    | now = Now. e.g. "now"    
    | jd = Julian day. e.g. 24504527.45678
    | iso = ISO 8601. e.g. 2018-02-28T12:34:55.23
    | sql = ISO 8601. e.g. 2018-02-28 12:34:55.23
    | ymdhms = Calendar. e.g. 2018 2 28 12 34 55.23
    | equinox = Equinox. e.g. J2000,0
    | digits = Pure digits e.g. 20180228123455.23
4f8cc5f0   aklotz   Package CelMe Cel...
25
    
17d8b9ff   aklotz   celme mise à jour.
26
27
    
    *Usage:*
4f8cc5f0   aklotz   Package CelMe Cel...
28

17d8b9ff   aklotz   celme mise à jour.
29
30
31
32
    First, instanciate an object from the class: 
    
    ::
        date = Date()
4f8cc5f0   aklotz   Package CelMe Cel...
33
34

    Second, assign a date in any date format:
17d8b9ff   aklotz   celme mise à jour.
35
36
37
38
39
40
41
42
43
44
45
46
    
    ::
        date.date("2018-02-28T12:34:55")

    Third, get the converted date:
    
    ::
        jd = date.jd()
        date = date.date()
        iso = date.iso()
        ymdhms = date.ymdhms()
        equinox = date.equinox()
4f8cc5f0   aklotz   Package CelMe Cel...
47

17d8b9ff   aklotz   celme mise à jour.
48
    *Informations:*
4f8cc5f0   aklotz   Package CelMe Cel...
49

4f8cc5f0   aklotz   Package CelMe Cel...
50
    All dates are in UTC.
17d8b9ff   aklotz   celme mise à jour.
51
    Some other useful methods:
4f8cc5f0   aklotz   Package CelMe Cel...
52
    
17d8b9ff   aklotz   celme mise à jour.
53
54
55
56
57
    ::
        help(Date)
        Date().infos("doctest")
        Date().infos("doc_methods")
        
4f8cc5f0   aklotz   Package CelMe Cel...
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
    """
# ========================================================
# === attributs
# ========================================================

    _B1850 = 2396758.203
    _B1900 = 2415020.3135
    _B1950 = 2433282.4235
    _B1975 = 2442413.478
    _B2000 = 2451544.533
    _B2025 = 2460675.588
    _B2050 = 2469806.643
    _B2100 = 2488068.753
    _J1900 = 2415020.0000
    _J1950 = 2433282.5000
    _J2000 = 2451545.0000
    _J2050 = 2469807.5000
    _J2100 = 2488070.0000

# ========================================================
# === internal methods
# ========================================================

17d8b9ff   aklotz   celme mise à jour.
81
    def _init(self,date="") -> None:
4f8cc5f0   aklotz   Package CelMe Cel...
82
83
84
85
        """ Initialize internal attributes.

        :param date: date is a date in any supported format (cf. help(Date))
        :type date: any 
17d8b9ff   aklotz   celme mise à jour.
86
        :returns: None
4f8cc5f0   aklotz   Package CelMe Cel...
87
88
89
90
91
92
93
94
95
96
97
        :rtype: None
 
        :Example:
            
        >>> objdate = Date()
        >>> objdate._init()
        
        """
        self._init_date = date
        self._init_dateformat = 0
        self._computed_jd = 0
4f8cc5f0   aklotz   Package CelMe Cel...
98
99
100
101
102
103
104
105
106
107
        self._computed_iso = 0
        self._computed_iso_nb_subdigit = 3
        self._computed_iso_letter = 'T'
        self._computed_ymdhms = 0
        self._computed_digits = 0
        self._computed_digits_nb_subdigit = 3
        self._computed_equinox = 0
        self._computed_equinox_year_type = "J"
        self._computed_equinox_nb_subdigit = 1
        self._jd = 0
4f8cc5f0   aklotz   Package CelMe Cel...
108
109
110
111
112
113
114
115
116
        self._iso = 0
        self._ymdhms = 0
        self._equinox = 0

    def _is_number(self,s) -> bool:
        """ Return True if the string is a number else return False.

        :param s: A string to test
        :type s: string
17d8b9ff   aklotz   celme mise à jour.
117
        :returns: True is the string can be concerted into a float
4f8cc5f0   aklotz   Package CelMe Cel...
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
        :rtype: bool
 
        :Example:

        >>> objdate = Date()
        >>> objdate._is_number("3e5")
        True
        >>> objdate._is_number("3a5")
        False
        
        """
        try:
            float(s)
            return True
        except ValueError:
            pass 
        try:
            import unicodedata
            unicodedata.numeric(s)
            return True
        except (TypeError, ValueError):
            pass 
        return False

    def _duration2day(self, duration) -> float:
        """ Return a duration in day unit from a duration in dhms format.

        :param duration: A string formated as "2d7h23m12.5s"
        :type duration: string
17d8b9ff   aklotz   celme mise à jour.
147
        :returns: duration expressed in day and fraction of day
4f8cc5f0   aklotz   Package CelMe Cel...
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
        :rtype: float
 
        :Example:

        >>> objdate = Date()
        >>> objdate._duration2day("2d7h23m12.5s")
        2.3077835648148146
        
        """
        duration = str(duration)
        duration = duration.upper()
        cars = "+-.E0123456789"
        units = "DHMS"
        dur = 0
        k1 = -1
        k2 = -1
        k = 0
        div = 0
        for car in duration:
            if car in cars:
                if k1 == -1:
                    k1 = k
                k2 = k
            elif car in units:                
                if (k1>=0 and k2>=0):
                    div = 0
                    if car=='D':
                        div = 1.
                    elif car=='H':
                        div = 24.
                    elif car=='M':
                        div = 1440.
                    elif car=='S':
                        div = 86400.
                    if div>0:
                        n = float(duration[k1:k2+1])
                        dur += n/div
                    k1 = -1
                    k2 = -1
            k += 1
        if (div==0 and dur==0 and k1>=0 and k2>=k1):
            n = float(duration[k1:k2+1])
            dur += n
        return dur
    
    def _date_compare(self, date, operator):
        """ Comparaison of dates for various operators.

        :param date: A date in any supported format (cf. help(Date))
        :type date: Date()
        :param operator : Operator such as == != > >= < <=
        :type operator : string
17d8b9ff   aklotz   celme mise à jour.
200
        :returns: The logic result of the comparison.
4f8cc5f0   aklotz   Package CelMe Cel...
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
        :rtype: bool
        
        :Example:

        >>> objdate1 = Date()
        >>> objdate2 = Date()
        >>> objdate1.date("2018 02 28"); objdate2.date("2018 02 27"); objdate1._date_compare(objdate2,">")
        '2018 02 28'
        '2018 02 27'
        True
        
        .. note:: Does not account for the modulo.
        """
        if self._computed_jd == 0:
            self.jd()
        if date._computed_jd == 0:
            date.jd()
        res = False
        if (self._computed_jd == 1) and (date._computed_jd == 1):
            toeval = str(self._jd)+" "+operator+" "+str(date._jd)
            res = eval(toeval)
        return res
    
# ========================================================
# === date methods
# ========================================================

    def date_date2jd(self,date) -> typing.Tuple[int, float]:
        """ Compute a julian day from any date format

        :param date: A string formated as "2d7h23m12.5s"
        :type date: string
17d8b9ff   aklotz   celme mise à jour.
233
234
235
236
237
238
239
240
241
242
        :returns: A tuple of init_dateformat, julian day. init_dateformat: The identified format of the input:
            * 0 = Error, format not known
            * 1 = Now
            * 2 = Equinox
            * 3 = Sql
            * 4 = Calendar
            * 5 = ISO 8601
            * 6 = Julian day
            * 7 = Modified Julian day
            * 8 = Digits
4f8cc5f0   aklotz   Package CelMe Cel...
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
        :rtype: tuple(int, float)
 
        :Example:

        >>> objdate = Date()
        >>> objdate.date_date2jd("2018-02-28T12:34:55.234")
        (5, 2458178.0242503937)
                
        .. note:: Prefer using objdate.date() followed by objdate.jd().            
        """
        # --- First we do not process if date is ever a Date object
        if (isinstance(date, Date)):
            return date
        # --- Decode the date
        jd = 0
        init_dateformat = 0
        str_date = str(date).upper()
        str_split = str_date.split(" ")
        str_nsplit = len(str_split)
        if str_date == "NOW":
            # style NOW
            utc_datetime = datetime.datetime.utcnow()
            day = utc_datetime.day + ((((utc_datetime.microsecond*1e-6) + utc_datetime.second)/60. + utc_datetime.minute)/60. + utc_datetime.hour)/24.
            error, jd = self.date_ymd2jd(utc_datetime.year, utc_datetime.month, day)
            init_dateformat = 1
17d8b9ff   aklotz   celme mise à jour.
268
        elif (str_date[0] == "B") or (str_date[0] == "J"):
4f8cc5f0   aklotz   Package CelMe Cel...
269
270
271
            # style J2000,0
            error, jd = self.date_equinox2jd(str_date)
            init_dateformat = 2
17d8b9ff   aklotz   celme mise à jour.
272
        elif (str_nsplit == 2):
4f8cc5f0   aklotz   Package CelMe Cel...
273
274
275
276
            # style SQL 2018-01-02 23:02:45.456
            iso_date = str_split[0] + "T" + str_split[1]
            error, jd = self.date_iso2jd(iso_date)
            init_dateformat = 3
17d8b9ff   aklotz   celme mise à jour.
277
        elif (str_nsplit == 3):
4f8cc5f0   aklotz   Package CelMe Cel...
278
279
280
281
            # style calenday 2018 01 02.4567
            str_split = [ float(x) for x in str_split]
            error, jd = self.date_ymd2jd(str_split[0],str_split[1],str_split[2])
            init_dateformat = 4
17d8b9ff   aklotz   celme mise à jour.
282
        elif (str_nsplit == 4):
4f8cc5f0   aklotz   Package CelMe Cel...
283
284
285
286
            # style calenday 2018 01 02 05.324
            str_split = [ float(x) for x in str_split]
            error, jd = self.date_ymdhms2jd(str_split[0],str_split[1],str_split[2],str_split[3])
            init_dateformat = 4
17d8b9ff   aklotz   celme mise à jour.
287
        elif (str_nsplit == 5):
4f8cc5f0   aklotz   Package CelMe Cel...
288
289
290
291
            # style calenday 2018 01 02 05 12.1809
            str_split = [ float(x) for x in str_split]
            error, jd = self.date_ymdhms2jd(str_split[0],str_split[1],str_split[2],str_split[3],str_split[4])
            init_dateformat = 4
17d8b9ff   aklotz   celme mise à jour.
292
        elif (str_nsplit == 6):
4f8cc5f0   aklotz   Package CelMe Cel...
293
294
295
296
            # style calenday 2018 01 02 05 12 56.789
            str_split = [ float(x) for x in str_split]
            error, jd = self.date_ymdhms2jd(str_split[0],str_split[1],str_split[2],str_split[3],str_split[4],str_split[5])
            init_dateformat = 4
17d8b9ff   aklotz   celme mise à jour.
297
        elif (str_nsplit == 1) and (str_date.find("T") > 6):
4f8cc5f0   aklotz   Package CelMe Cel...
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
            # style ISO 2018-01-02T23:02:45.456
            error, jd = self.date_iso2jd(str_date)
            init_dateformat = 5
        elif (self._is_number(str_date) is True):
            # style is julian day or MJD   
            # MJD = JD - 2400000.5 (SAO in 1957)
            # digits as 20180316
            jd = float(str_date)
            init_dateformat = 6
            if (math.log10(jd) > 7.2):
                # --- digits
                error, jd = self.date_digits2jd(str_date)
                init_dateformat = 8
            elif (math.log10(jd) < 5):
                # --- MJD
                jd += 2400000.5
                init_dateformat = 7
        return init_dateformat, jd
        
17d8b9ff   aklotz   celme mise à jour.
317
    def date_iso2jd(self,string) -> tuple:
4f8cc5f0   aklotz   Package CelMe Cel...
318
319
320
321
        """ Compute a julian day from a ISO8601 date

        :param string: A string formated in ISO 8601
        :type string: string
17d8b9ff   aklotz   celme mise à jour.
322
        :returns: A tuple of error, julian day. error = 0 means no error
4f8cc5f0   aklotz   Package CelMe Cel...
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
        :rtype: tuple(int, float)
 
        :Example:

        >>> objdate = Date()
        >>> objdate.date_iso2jd("2018-02-28T12:34:55.234")
        (0, 2458178.0242503937)
        
        First integer is an error code. 0 = no problem.
            
        .. note:: Prefer using objdate.date() followed by objdate.jd().            
        """
        error = 0
        k1 = string.find("-",1)
        k2 = string.find("-",k1+1)
        kt = string.find("T",k2+1)
        if (kt==-1):
            kt = string.find("T",k2+1)
        k3 = string.find(":",kt+1)
        k4 = string.find(":",k3+1)
        d=1
        hh=0
        mm=0
        ss=0.0
        if (k2 > -1): 
            y = int(string[0:k1])
            m = int(string[k1+1:k2])
            if (kt == -1):
                d = float(string[k2+1:])
            else:
                d = int(string[k2+1:kt])
            if (k3 > -1):
                hh = int(string[kt+1:k3])
                d += hh/24.
            if (k4 == -1):
                mm = float(string[k3+1:])
                d += mm/1440.
            else:
                mm = int(string[k3+1:k4])
                d += mm/1440.
                ss = float(string[k4+1:])
                d += ss/86400.                
            error, jd = self.date_ymd2jd(y,m,d)
        else:
            # pb format
            error = 1
        return error, jd

17d8b9ff   aklotz   celme mise à jour.
371
    def date_jd2iso(self, jd, nb_subdigit=3, letter='T') -> tuple:
4f8cc5f0   aklotz   Package CelMe Cel...
372
373
374
375
        """ Compute a ISO8601 date from a julian day

        :param jd: A julian day
        :type jd: float
17d8b9ff   aklotz   celme mise à jour.
376
        :param nb_subdigit: The number of digits returned after the seconds.
4f8cc5f0   aklotz   Package CelMe Cel...
377
        :type nb_subdigit: int
17d8b9ff   aklotz   celme mise à jour.
378
        :param letter: The letter to separe date end time. If letter is "" then the output format sticks all digits without any characters :-T. So the format is no longer ISO but useful for a pure digit code.
4f8cc5f0   aklotz   Package CelMe Cel...
379
        :type letter: int
17d8b9ff   aklotz   celme mise à jour.
380
        :returns: A tuple of error, string of a date formatted into ISO8601. error = 0 means no error.
4f8cc5f0   aklotz   Package CelMe Cel...
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
        :rtype: tuple(int, float)
 
        :Example:

        >>> objdate = Date()
        >>> objdate.date_jd2iso(2458178.0242503937)
        (0, '2018-02-28T12:34:55.234')
        
        .. note:: Prefer using objdate.date() followed by objdate.iso()            
        """
        error, y, m, d, hh, mm, ss = self.date_jd2ymdhms(jd)
        nb_prefixdigit = nb_subdigit+3
        if (nb_subdigit < 0):
            nb_subdigit = 0
        if (nb_subdigit == 0):
            nb_prefixdigit -= 1
        if (letter==''):
            fstring  = "{:04d}{:02d}{:02d}{}{:02d}{:02d}{:0"+str(nb_prefixdigit)+"."+str(nb_subdigit)+"f}"
        else:
            fstring  = "{:04d}-{:02d}-{:02d}{}{:02d}:{:02d}:{:0"+str(nb_prefixdigit)+"."+str(nb_subdigit)+"f}"
        res = fstring.format(y, m, d, letter, hh, mm, ss)
        return error, res
                
    def date_equinox2jd(self,string):
        """ Compute a julian day from a equinoxal date
        
        :param string: date string is a string in Equinox format (cf. help(Date))
        :type string: string 
17d8b9ff   aklotz   celme mise à jour.
409
        :returns: A tuple of error, julian day. error = 0 means no error
4f8cc5f0   aklotz   Package CelMe Cel...
410
411
412
        :rtype: tuple(int, float)
 
        :Example:
17d8b9ff   aklotz   celme mise à jour.
413
        
4f8cc5f0   aklotz   Package CelMe Cel...
414
415
416
417
418
419
420
421
422
423
424
        >>> objdate = Date()
        >>> objdate.date_equinox2jd("J2025,0")
        (0, 2460676.25)
        
        .. note:: Prefer using objdate.date() followed by objdate.jd()            
        """
        error = 0
        t = string[0]
        s = string[1:].replace(',','.')
        a = float(s)
        jd = 0
17d8b9ff   aklotz   celme mise à jour.